Встроенный в PHP веб-сервер — Веб-разработка на PHP
PHP, как и многие другие языки, сразу поставляется со встроенным веб-сервером. Этот веб-сервер создан исключительно для удобства разработки, так как не надо ставить ничего дополнительно, но совсем не подходит для продакшен среды. В последнем случае нужно использовать nginx.
Разработка сайтов, с точки зрения организации кодовой базы, мало отличается от разработки обычных программ. Первым делом необходимо создать директорию внутри которой будет вестись разработка сайта, а затем её следует добавить в git-репозиторий. Назовём эту директорию корнем проекта. Если проект учебный, то лучше сразу создать репозиторий на GitHub и выкладывать все эксперименты туда.
Затем нужно создать файл index.php и поместить его в корень проекта. По соглашению это главный входной файл в PHP, который автоматически ищется веб-серверами. Создайте такой файл в директории проекта со следующим содержимым:
// Печатает год в STDOUT echo date('Y'); echo "\n";
Затем запустите веб-сервер, например, на порту 8080 .
-S localhost:8080 [Wed May 27 11:55:19 2020] PHP 7.4.3 Development Server (http://localhost:8080) started
После того как сервер будет запущен, он полностью забирает управление. Вкладка терминала больше не доступна для ввода команд. В отличие от обычных скриптов, которые выполняют свою задачу и заканчиваются, веб-сервера должны слушать порт непрерывно и сразу реагировать на входящие соединения. Поэтому однажды запустив сервер продолжит работать до тех пор, пока его не остановят. Остановить сервер можно, набрав Ctrl-C .
Такой способ запуска удобен в разработке, но в реальном окружении сервера запускают в виде демонов. Демон — процесс операционной системы, работающий в фоне.
Если в это время попытаться запустить ещё один веб-сервер в соседней вкладке на том же порту, то запуск завершится с такой ошибкой:
Failed to listen on localhost:8080 (reason: Address already in use)
В своей программистской жизни вы встретитесь с этой ошибкой не раз. Она означает, что какой-то процесс занял соответствующий порт (в данном случае 8080). В такой ситуации нужно либо остановить процесс который вам мешает, либо стартовать на другом порту.
Посмотреть какой процесс занял порт 8080 можно командой sudo lsof -i :8080
После этого откройте браузер и введите http://localhost:8080 . На экран выведется текущий год. В терминале, где запущен веб-сервер, появятся записи (лог), показывающие входящие запросы.
[Wed May 27 14:53:31 2020] [::1]:52988 [200]: GET / [Wed May 27 14:53:31 2020] [::1]:52990 [404]: GET /favicon.ico - No such file or directory
Теперь снова откройте файл index.php и добавьте ниже вывод echo ‘Hello, world!’; . Выполните f5 в браузере, и вы увидите, что изменения применились автоматически. Так происходит, потому что веб-сервер запускает файл на выполнение заново при каждом http запросе.
Тело HTTP-ответа
При запуске скриптов на PHP, любая функция, печатающая на экран, предсказуемо печатает на экран:
Открыть доступ
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно
- 130 курсов, 2000+ часов теории
- 1000 практических заданий в браузере
- 360 000 студентов
Наши выпускники работают в компаниях:
Php run http server
This web server is designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.
The CLI SAPI provides a built-in web server.
The web server runs only one single-threaded process, so PHP applications will stall if a request is blocked.
URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached. If an index.php or index.html is found, it is returned and $_SERVER[‘PATH_INFO’] is set to the trailing part of the URI. Otherwise a 404 response code is returned.
If a PHP file is given on the command line when the web server is started it is treated as a «router» script. The script is run at the start of each HTTP request. If this script returns false , then the requested resource is returned as-is. Otherwise the script’s output is returned to the browser.
Standard MIME types are returned for files with extensions: .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, and .zip.
Version | Description |
---|---|
5.5.12 | .xml, .xsl, and .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, and .zip |
5.5.5 | |
5.4.11 | .ogg, .ogv, and .webm |
5.4.4 | .htm and .svg |
Version | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7.4.0 | You can configure the built-in webserver to fork multiple workers in order to test code that requires multiple concurrent requests to the built-in webserver. Set the PHP_CLI_SERVER_WORKERS environment variable to the number of desired workers before starting the server. This is not supported on Windows. This experimental feature is not intended for production usage. Generally, the built-in Web Server is not intended for production usage. Example #1 Starting the web server $ cd ~/public_html $ php -S localhost:8000 Встроенный web-серверЭтот web-сервер был разработан для помощи в разработке. Он также может быть полезным в тестовых целях или для демонстрации приложения, запускаемого в полностью контролируемом окружении. Он не выполняет функции полноценного web-сервера и не должен использоваться во общедоступных сетях. Начиная с версии PHP 5.4.0 модуль CLI SAPI содержит встроенный web-сервер. Если запрос блокирующий, то PHP приложения будут приостановлены. URI запросы обслуживаются из текущей директории, в которой был запущен PHP, если не используется опция -t для явного указания корневого документа. Если URI запроса не указывает на определенный файл, то будет возвращен либо index.php либо index.html в указанной директории. Если оба файла отсутствуют, то возвращается 404 код ответа. Если PHP-файл указывается в командной строке, когда запускается веб-сервер, то он рассматривается как скрипт «маршрутизации». Скрипт выполняется в самом начале после каждого 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.
Пример #1 Запуск web-сервера $ cd ~/public_html $ php -S localhost:8000 PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011 Listening on localhost:8000 Document root is /home/me/public_html Press Ctrl-C to quit После URI запросов http://localhost:8000/ и http://localhost:8000/myscript.html в консоли выведется примерно следующее: PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011 Listening on localhost:8000 Document root is /home/me/public_html Press Ctrl-C to quit. [Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read [Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read [Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read [Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read [Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read Пример #2 Запуск с указанием корневой директории $ cd ~/public_html $ php -S localhost:8000 -t foo/ PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011 Listening on localhost:8000 Document root is /home/me/public_html/foo Press Ctrl-C to quit Пример #3 Использование скрипта маршрутизации В этом примере, запросы изображений будут возвращать их, но запросы HTML файлов будут возвращать «Welcome to PHP». // router.php Welcome to PHP » ; $ php -S localhost:8000 router.php Пример #4 Проверка использования CLI web-сервера Для совместного использования скрипта маршрутизации при разработке с CLI web-сервером и в дальнейшем с боевым web-сервером: // router.php $ php -S localhost:8000 router.php Пример #5 Поддержка неподдерживаемых типов файлов Если вам нужно обслуживать статические ресурсы с MIME типами неподдерживаемыми CLI web-сервером: // router.php $ php -S localhost:8000 router.php Пример #6 Доступ к CLI web-серверу с удаленных машин Вы можете сделать web-сервер доступным на 8000 порту для всех сетевых интерфейсов: PHP Built-in Web ServerStarting from PHP 5.4 , PHP incorporates a feature of a built-in web server. You can take the advantage of PHP built-in web server for development and testing of your PHP applications. It means you don’t need to configure Apache virtual host to run your PHP applications. If you have already installed LAMP, WAMP, XAMPP on your system, still you can try and use this feature. To use PHP built-in web server you need to install PHP 5.4 or higher version. If you are not sure which PHP version you have installed on your machine, just open the terminal and type a simple command (php -v). I have already installed PHP version 5.5. To check some of the options by typing PHP -h (PHP help command) on a terminal. — c Look at the line marked in bold (-S, -t) this is the option for running PHP built-in web server. How to Start a PHP Built-in Web ServerTo use a PHP built-in web server, go to the root directory of your project and run this simple command on a terminal. Using this command a simple Web Server will run and listen to a port 8000. You can specify any port. If specified port is used by some other process, it will throw an error. [ Sat Oct 25 10 : 43 : 00 2014 ] Failed to listen on localhost : 8080 ( reason : Address already in use )When a web server is running successfully then the following output will be displayed on a terminal. When a web server is started, by default your current directory is your document root. If you want to change the document root, you can specify them with -t flag. Here, /var/www/laravel is my document root and I can request all the files present in a laravel directory. As per PHP Manual: Warning: This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network. ConclusionRemember this is a great feature for testing your PHP applications but it’s not a full-featured web server. I have written this post based on my experience with PHP built-in web server. If you are using this feature and you want to add something, you can let us know through your comment. |