- PHP Superglobal — $_SERVER
- PHP $_SERVER
- Example
- Server functions in php
- PHP $_SERVER
- Introduction to PHP $_SERVER
- Working of $_ SERVER Function
- Example of PHP $_SERVER
- 1. $_Server[‘PHP_SELF’]
- 2. $_SERVER[‘argv’]
- 3. $_SERVER[‘argc’]
- 4. $_Server[‘GATEWAY_INTERFACE’]
- 5. $_SERVER[‘SERVER_ADDR’]
- 6. $_SERVER[‘SERVER_SOFTWARE’]
- 7. $_SERVER[‘SERVER_PROTOCOL’]
- 8. $_SERVER[‘REQUEST_METHOD’]
- 9. $_SERVER[‘REQUEST_TIME’]
- 10. $_SERVER[‘QUERY_STRING’]
- 11. $_SERVER[‘HTTP_ACCEPT’]
- 12. $_SERVER[‘HTTP_HOST’]
- 13. $_SERVER[‘HTTP_REFERER’]
- 14. $_SERVER[‘REMOTE_HOST’]
- Conclusion
- Recommended Articles
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’];
?>?php>
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 |
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.
Версия | Описание |
---|---|
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 | |
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 |