Server functions in php

PHP Superglobal — $_SERVER

Super global variables are built-in variables that are always available in all scopes.

PHP $_SERVER

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

The example below shows how to use some of the elements in $_SERVER:

Example

echo $_SERVER[‘PHP_SELF’];
echo «
«;
echo $_SERVER[‘SERVER_NAME’];
echo «
«;
echo $_SERVER[‘HTTP_HOST’];
echo «
«;
echo $_SERVER[‘HTTP_REFERER’];
echo «
«;
echo $_SERVER[‘HTTP_USER_AGENT’];
echo «
«;
echo $_SERVER[‘SCRIPT_NAME’];
?>

The following table lists the most important elements that can go inside $_SERVER:

Element/Code Description
$_SERVER[‘PHP_SELF’] Returns the filename of the currently executing script
$_SERVER[‘GATEWAY_INTERFACE’] Returns the version of the Common Gateway Interface (CGI) the server is using
$_SERVER[‘SERVER_ADDR’] Returns the IP address of the host server
$_SERVER[‘SERVER_NAME’] Returns the name of the host server (such as www.w3schools.com)
$_SERVER[‘SERVER_SOFTWARE’] Returns the server identification string (such as Apache/2.2.24)
$_SERVER[‘SERVER_PROTOCOL’] Returns the name and revision of the information protocol (such as HTTP/1.1)
$_SERVER[‘REQUEST_METHOD’] Returns the request method used to access the page (such as POST)
$_SERVER[‘REQUEST_TIME’] Returns the timestamp of the start of the request (such as 1377687496)
$_SERVER[‘QUERY_STRING’] Returns the query string if the page is accessed via a query string
$_SERVER[‘HTTP_ACCEPT’] Returns the Accept header from the current request
$_SERVER[‘HTTP_ACCEPT_CHARSET’] Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1)
$_SERVER[‘HTTP_HOST’] Returns the Host header from the current request
$_SERVER[‘HTTP_REFERER’] Returns the complete URL of the current page (not reliable because not all user-agents support it)
$_SERVER[‘HTTPS’] Is the script queried through a secure HTTP protocol
$_SERVER[‘REMOTE_ADDR’] Returns the IP address from where the user is viewing the current page
$_SERVER[‘REMOTE_HOST’] Returns the Host name from where the user is viewing the current page
$_SERVER[‘REMOTE_PORT’] Returns the port being used on the user’s machine to communicate with the web server
$_SERVER[‘SCRIPT_FILENAME’] Returns the absolute pathname of the currently executing script
$_SERVER[‘SERVER_ADMIN’] Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on a virtual host, it will be the value defined for that virtual host) (such as someone@w3schools.com)
$_SERVER[‘SERVER_PORT’] Returns the port on the server machine being used by the web server for communication (such as 80)
$_SERVER[‘SERVER_SIGNATURE’] Returns the server version and virtual host name which are added to server-generated pages
$_SERVER[‘PATH_TRANSLATED’] Returns the file system based path to the current script
$_SERVER[‘SCRIPT_NAME’] Returns the path of the current script
$_SERVER[‘SCRIPT_URI’] Returns the URI of the current page
Читайте также:  Html get submit button name

Источник

Server functions in php

Веб-сервер предназначен для помощи в разработке приложений. Он также может быть полезным в тестовых целях или для демонстрации приложения, запускаемого в полностью контролируемом окружении. Он не выполняет функции полноценного веб-сервера и не должен использоваться в общедоступных сетях.

Модуль CLI SAPI содержит встроенный веб-сервер.

Веб-сервер выполняет только один однопоточный процесс, поэтому приложения PHP будут останавливаться, если запрос заблокирован.

URI запросы обслуживаются из текущей директории, в которой был запущен PHP, если не используется опция -t для явного указания корневого документа. Если URI запроса не указывает на определённый файл, то будет возвращён index.php или index.html в указанной директории. Если ни один из файлов не существует, то поиск этих файлов будет продолжен в родительской директории и так далее до тех пор, пока они не будут найдены или был достигнут корень документа. Если найден index.php или index.html, он возвращается, а в $_SERVER[‘PATH_INFO’] будет находится последняя часть URL. В противном случае возвращается 404 код ответа.

Если PHP-файл указывается в командной строке, когда запускается веб-сервер, то он рассматривается как скрипт «маршрутизации» (router). Скрипт выполняется в самом начале каждого HTTP-запроса. Если этот скрипт возвращает false , то запрашиваемый ресурс возвращается как есть. В противном случае браузеру будет возвращён вывод этого скрипта.

Стандартные MIME-типы возвращаются для файлов со следующими расширениями: .3gp, .apk, .avi, .bmp, .css, .csv, .doc, .docx, .flac, .gif, .gz, .gzip, .htm, .html, .ics, .jpe, .jpeg, .jpg, .js, .kml, .kmz, .m4a, .mov, .mp3, .mp4, .mpeg, .mpg, .odp, .ods, .odt, .oga, .ogg, .ogv, .pdf, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd и .zip.

История правок: Поддерживаемые MIME-типы (расширения файлов)

Версия Описание
5.5.12 .xml, .xsl, и .xsd
5.5.7 .3gp, .apk, .avi, .bmp, .csv, .doc, .docx, .flac, .gz, .gzip, .ics, .kml, .kmz, .m4a, .mp3, .mp4, .mpg, .mpeg, .mov, .odp, .ods, .odt, .oga, .pdf, .pptx, .pps, .qt, .swf, .tar, .text, .tif, .wav, .wmv, .xls, .xlsx и .zip
5.5.5 .pdf
5.4.11 .ogg, .ogv, и .webm
5.4.4 .htm и .svg
История изменений
Версия Описание
7.4.0 Вы можете настроить встроенный веб-сервер так, чтобы он выполнял разветвление нескольких воркеров для проверки кода, который требует нескольких одновременных запросов к встроенному веб-серверу. Задайте в переменной окружения PHP_CLI_SERVER_WORKERS количество требуемых воркеров перед запуском сервера. Не поддерживается в Windows.

Эта экспериментальная функция не предназначена для продакшен использования. Обычно встроенный веб-сервер не предназначен для продакшен использования.

Пример #1 Запуск веб-сервера

$ cd ~/public_html $ php -S localhost:8000

Источник

PHP $_SERVER

PHP <img decoding=

PHP comes out as a function of $_Server, which is a super global variable in PHP having information about paths and headers. Basically, these super variables are always available in the scope of any PHP code.

Web development, programming languages, Software testing & others

$_Server consists of an array that has the information created by the web server, such as headers, path, scriptlocations. It is directly related to the runtime environment of the current PHP script. All the information regarding the server can be get using this function. This is available from PHP version 4 and higher.

The Syntax for getting details using $ server function is:-

The variable name contains the name of the information we need to get from the $server method.

For Ex:- Suppose we want to get the Server Name.

So from this, we can get the details of whatever is required for that PHP environment.

PHP <img decoding=

  • The $_Server Function is a super global variable in PHP.
  • $_ Server gets the information of the headers, path, and location of the script from the web server in the form of an Array.
  • $_Server is basically set by the web server where the PHP code is deployed. There is no guarantee that the thing that server will provide all the details required; sometimes, there may be a case where the information is not listed, and sometimes some excess information can also come in place. It is directly related to the scripts at the run time.

Example of PHP $_SERVER

Let us see some functioning of $ Server with some examples:

1. $_Server[‘PHP_SELF’]

This defines the file name of the script where the current PHP code is being run. This gives the path of the PHP.

SERVER-1.1″ width=»141″ height=»36″/>SERVER-1.1″ width=»141″ height=»36″/>

2. $_SERVER[‘argv’]

This stores the argument passed in an array, and the return type for this is an array.

SERVER-1.2″ width=»73″ height=»33″/>SERVER-1.2″ width=»73″ height=»33″/>

3. $_SERVER[‘argc’]

This gives information about the number of command line parameters.

SERVER-1.3″ width=»63″ height=»37″/>SERVER-1.3″ width=»63″ height=»37″/>

4. $_Server[‘GATEWAY_INTERFACE’]

This gives information about the common gateway interface, if any. If there is no gateway used, the result obtained is null.

Blank as no Gateway interface is used.

5. $_SERVER[‘SERVER_ADDR’]

It returns the IP address of the host server where the PHP script is being run. If ran on local, this gives the local IP address of the machine.

The IP address of the host machine.

6. $_SERVER[‘SERVER_SOFTWARE’]

This gives the detail of the software used in the server. this may be Apache or any hosted web servers.

7. $_SERVER[‘SERVER_PROTOCOL’]

This gives the detail of the protocol via the request made. HTTP , HTTPS are the most probable information for this function.

8. $_SERVER[‘REQUEST_METHOD’]

This gives the detail of the request method used to access a particular page.

9. $_SERVER[‘REQUEST_TIME’]

This records the timestamp for the start of any request.

SERVER-1.4″ width=»121″ height=»38″/>SERVER-1.4″ width=»121″ height=»38″/>

10. $_SERVER[‘QUERY_STRING’]

If any query is used for accessing the page, this method gives the information about that.

If query used the Query or else none.

11. $_SERVER[‘HTTP_ACCEPT’]

It gives the details of the acceptance of the HTTP request if it exists or else none.

The accept request if exists else none.

12. $_SERVER[‘HTTP_HOST’]

It gives the name of the host where the server is hosted.

13. $_SERVER[‘HTTP_REFERER’]

This returns the complete URL of the current page.

14. $_SERVER[‘REMOTE_HOST’]

It gives the host name from where the user is viewing the page.

The host name from where the page is accessed.

$_SERVER['SERVER_PORT'],$_SERVER['SERVER_SIGNATURE'], $_SERVER['PATH_TRANSLATED'], $_SERVER['SCRIPT_NAME'], $_SERVER['SCRIPT_URI']

Note: Some of the screenshots didn’t have the output, as the output depends on the configuration we have set for the particular PHP server.

Conclusion

From the above article, we saw the use of Function $Server in PHP. We also saw the internal working and the advantages of having the type of data which we are defining for various programming purposes. Also, the syntax and examples helped us to understand much precisely the function.

This is a guide to PHP $_SERVER. Here we also discuss the introduction and working of the $_ server function along with different examples and its code implementation. You may also have a look at the following articles to learn more –

25+ Hours of HD Videos
5 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

92+ Hours of HD Videos
22 Courses
2 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

83+ Hours of HD Videos
16 Courses
1 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

PHP Course Bundle — 8 Courses in 1 | 3 Mock Tests
43+ Hours of HD Videos
8 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Оцените статью