Php server url port
Веб-сервер предназначен для помощи в разработке приложений. Он также может быть полезным в тестовых целях или для демонстрации приложения, запускаемого в полностью контролируемом окружении. Он не выполняет функции полноценного веб-сервера и не должен использоваться в общедоступных сетях.
Модуль 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 $_SERVER$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server, therefore there is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. However, most of these variables are accounted for in the » CGI/1.1 specification, and are likely to be defined.
In addition to the elements listed below, PHP will create additional elements with values from request headers. These entries will be named HTTP_ followed by the header name, capitalized and with underscores instead of hyphens. For example, the Accept-Language header would be available as $_SERVER[‘HTTP_ACCEPT_LANGUAGE’] . Indices‘ PHP_SELF ‘ The filename of the currently executing script, relative to the document root. For instance, $_SERVER[‘PHP_SELF’] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php . The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name. ‘argv’ Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. ‘argc’ Contains the number of command line parameters passed to the script (if run on the command line). ‘ GATEWAY_INTERFACE ‘ What revision of the CGI specification the server is using; e.g. ‘CGI/1.1’ . ‘ SERVER_ADDR ‘ The IP address of the server under which the current script is executing. ‘ SERVER_NAME ‘ The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
‘ SERVER_SOFTWARE ‘ Server identification string, given in the headers when responding to requests. ‘ SERVER_PROTOCOL ‘ Name and revision of the information protocol via which the page was requested; e.g. ‘HTTP/1.0’ ; ‘ REQUEST_METHOD ‘ Which request method was used to access the page; e.g. ‘GET’ , ‘HEAD’ , ‘POST’ , ‘PUT’ .
‘ REQUEST_TIME ‘ The timestamp of the start of the request. ‘ REQUEST_TIME_FLOAT ‘ The timestamp of the start of the request, with microsecond precision. ‘ QUERY_STRING ‘ The query string, if any, via which the page was accessed. ‘ DOCUMENT_ROOT ‘ The document root directory under which the current script is executing, as defined in the server’s configuration file. ‘ HTTPS ‘ Set to a non-empty value if the script was queried through the HTTPS protocol. ‘ REMOTE_ADDR ‘ The IP address from which the user is viewing the current page. ‘ REMOTE_HOST ‘ The Host name from which the user is viewing the current page. The reverse dns lookup is based on the REMOTE_ADDR of the user.
‘ REMOTE_PORT ‘ The port being used on the user’s machine to communicate with the web server. ‘ REMOTE_USER ‘ The authenticated user. ‘ REDIRECT_REMOTE_USER ‘ The authenticated user if the request is internally redirected. ‘ SCRIPT_FILENAME ‘ The absolute pathname of the currently executing script.
‘ SERVER_ADMIN ‘ The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host. ‘ SERVER_PORT ‘ The port on the server machine being used by the web server for communication. For default setups, this will be ’80’ ; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
‘ SERVER_SIGNATURE ‘ String containing the server version and virtual host name which are added to server-generated pages, if enabled. ‘ PATH_TRANSLATED ‘ Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.
‘ SCRIPT_NAME ‘ Contains the current script’s path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. ‘ REQUEST_URI ‘ The URI which was given in order to access this page; for instance, ‘ /index.html ‘. ‘ PHP_AUTH_DIGEST ‘ When doing Digest HTTP authentication this variable is set to the ‘Authorization’ header sent by the client (which you should then use to make the appropriate validation). ‘ PHP_AUTH_USER ‘ When doing HTTP authentication this variable is set to the username provided by the user. ‘ PHP_AUTH_PW ‘ When doing HTTP authentication this variable is set to the password provided by the user. ‘ AUTH_TYPE ‘ When doing HTTP authentication this variable is set to the authentication type. ‘ PATH_INFO ‘ Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URI http://www.example.com/php/path_info.php/some/stuff?foo=bar , then $_SERVER[‘PATH_INFO’] would contain /some/stuff . ‘ ORIG_PATH_INFO ‘ Original version of ‘ PATH_INFO ‘ before processed by PHP. ExamplesExample #1 $_SERVER example Массив $_SERVERОписание значений глобального массива $_SERVER с примерами. Параметры сервераИмя хоста, обычно совпадает с доменом. Название и версия сервера. Версия сервера и имя виртуального хоста, обычно пуста. Имя и версия используемого HTTP протокола. Значение из директивы конфигурационного файла Apache. Параметры соединенияИмя сервера, как правило, совпадает с доменом. IP-адрес, с которого пользователь просматривает текущую страницу. Удаленный хост, с которого пользователь просматривает текущую страницу. Порт на удаленной машине, который используется для связи с веб-сервером. Время запроса к серверу в Unix timestamp. Время запроса к серверу с точностью до микросекунд. Пути на сервереДиректория корня сайта, в которой выполняется текущий скрипт. Появился в Apache2, то же самое что и DOCUMENT_ROOT . Содержит путь, содержащийся после имени скрипта. Исходное значение переменной PATH_INFO перед обработкой PHP. Путь и имя выполняемого скрипта. Путь к исполняемому скрипту относительно корня сайта, обычно равен SCRIPT_NAME . Абсолютный путь к исполняемому скрипту. Авторизация на .htpasswdМетод HTTP аутентификации. $_SERVER[‘REMOTE_USER’] и $_SERVER[‘PHP_AUTH_USER’] HTTPS$_SERVER[‘HTTPS’] , $_SERVER[‘HTTP_X_HTTPS’] , $_SERVER[‘REDIRECT_HTTPS’] URLЗначения в примерах приведены для адреса http://site.ru/index.php?page=1&sort=2 URI страницы с GET-параметрами, без домена. Количество элементов массива $_SERVER[‘argv’] . Содержит URL страницы без GET-параметров и домена. Заголовки браузераСтрока, обозначающая браузер и операционную систему, который открыл данную страницу. Куки браузера в виде строки: ключ=значение; ключ=значение;. Адрес страницы, с которой браузер пользователя перешёл на текущую страницу. Содержимое заголовка Accept из текущего запроса. HTTP заголовок переданный клиентом, говорящий о том какие алгоритмы сжатия он может понять. Содержимое заголовка Accept-Language . Предпочтения клиента относительно кодировки. Значение заголовка Connection . Браузер отправляет этот заголовок со значением 1 , выражающий предпочтение клиента для зашифрованного ответа. Дамп переменной $ _SERVERДля тестирования, значения массива $ _SERVER для разных клиентов можно скидывать в лог-файл: |