I want to run the simple embedded webserver from php via command line
php -S 0.0.0.0:8000
and let it show the content of the current directory.
As of the man page the only possible additional option to -S is -t for the document root. I know I can just create a index.php file with the following content
<html>
<body>
<?php
$directory = "./";
$files = glob($directory . "*");
foreach($files as $file) {
echo "<a href=".rawurlencode($file).">".basename($file)."</a><br>";
}
?>
</body>
</html>
but I don’t want to create a file in that directory.
Isn’t it possible to run that code as a command line argument? I have tried it with the option -r and even with a virtual bash file and the -F-option as follows: -F <(… php code here …) but it seems true that the -S command only accepts -t as additional command.
Is there any trick to achieve it?
PS: I know that with python 2 or python 3 it is easily possible to show the current directory with python’s embedded webserver with
python -m SimpleHTTPServer # python 2
python -m http.server # python 3
but I want to do it with php.
Replace
"./"from the assignment of variable$directorywith the complete path of the directory you want to serve. Or, even better, change it to:to serve the path you provide as argument to
-tin the command line.Put
index.phpwherever you want in the file system and add its location (with complete path) to the end of thephpcommand line.If, for example, you save it as
/home/erik/index.php, start PHP as:PHP will use the script as a router. It will run it on every request and you can change it to interpret the request (
$_GET[],$_SERVER[]) and generate different output, depending of the requested path and query string.