On stackoverflow there are a lot of questions like “which server to put for php development”. Many people recommend apache2 and nginx + php-fpm. But today's article is about the possibility of a built-in php server.
The built-in server in php has appeared since version 5.4.0, and is launched by the command:
$ php -S localhost:8000 index.php
Where:
-S - start the server
localhost - host (ip address) on which the server will be
8000 - server port
index.php - request processing file
The server's routing is done using a php file that performs these functions, so, if this file returns `false`, the file will be requested directly; if this is not the case, the file that we specified as the router will be processed.
For example, if the following condition is added to the index.php file:
')
<?php if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) { return false;
Then, when requesting static files, they will be sent directly by the server, and any other request will be processed via index.php ...
Part 2. We write the system script and server in phpAnd so how to write a system script for linux? The answer is quite simple - first we need to specify the interpreter that will execute this script. Since we are writing a script in php, then we will indicate it with the interpreter in the first line:
Next, we will describe the parameters that the script receives from the console:
if(isset($argv[1])) { $host = $argv[1]; } else { help(); } if(isset($argv[2])) { $port = $argv[2]; } else { help(); }
Two simple if'a, which check the 1 and 2 argument, which will be the host and port, respectively, and if it is not, then displays the help () function.
function help() { echo " usage: phpServer host port ".PHP_EOL; exit(); }
And, at last, we add the instruction starting the server.
system(sprintf('php -S %s:%s', $host, $port));
After the script is ready, we change its rights and drop it into the / usr / bin / server folder.
$ chmod 0777 server $ sudo cp server /usr/bin/server
Well, that's all, now we just have to go to the project folder and start the server with a command.
$ server localhost 8080
To access the web part of the server, enter
localhost : 8080 in the address bar and proceed.
Conclusion: The built-in php server is intended only for development, and it is much more economical than apache2 and nginx + php-fpm ...