Skip to content

Instantly share code, notes, and snippets.

@jackmakiyama
Created October 21, 2015 19:33
Show Gist options
  • Save jackmakiyama/66254d729346ed91b89a to your computer and use it in GitHub Desktop.
Save jackmakiyama/66254d729346ed91b89a to your computer and use it in GitHub Desktop.
Run PHP built-in web server with no need of a router file.
#!/usr/bin/env php
<?php
/**
* Usage: php-server [ OPTIONS ] [ DOCUMENT_ROOT ]
*
* When not defined, DOCUMENT_ROOT is the current directory.
*
* -a, --application Defines the application file (default "index.php")
* -b, --background When defined runs server in background
* -h, --host Defines the host of the HTTP web server (default "127.0.0.1")
* -p, --port Defines the port of the HTTP web server (default "8888")
*
* Report bugs to Henrique Moody <henriquemoody@gmail.com>.
*/
set_exception_handler(function (Exception $exception) {
fwrite(STDERR, $exception->getMessage().PHP_EOL);
if (count($exception->getTrace()) > 1) {
fwrite(STDERR, $exception->getTraceAsString().PHP_EOL);
}
exit($exception->getCode() ?: 254);
});
$applicationFile = 'index.php';
$background = false;
$host = '127.0.0.1';
$port = 8888;
$workingDirectory = getcwd();
$arguments = $_SERVER['argv'];
array_shift($arguments);
while (($argument = array_shift($arguments))) {
if (in_array($argument, ['-b', '--background'])) {
$background = true;
continue;
}
if (in_array($argument, ['-a', '--application'])) {
$applicationFile = array_shift($arguments);
continue;
}
if (in_array($argument, ['-p', '--port'])) {
$port = array_shift($arguments);
continue;
}
if (in_array($argument, ['-h', '--host'])) {
$host = array_shift($arguments);
continue;
}
$workingDirectory = $argument;
}
if (!is_dir($workingDirectory)) {
throw new UnexpectedValueException(sprintf('"%s" is not a valid directory', $workingDirectory));
}
$basename = 'php-server_'.$host.'-'.$port;
$stdin = ['pipe', 'r'];
if (false === $background) {
$stdout = fopen('php://stdout', 'w');
$stderr = fopen('php://stderr', 'w');
} else {
$stdout = fopen('/tmp/'.$basename.'.log', 'w');
$stderr = $stdout;
}
$routerFilename = '/tmp/'.$basename.'.php';
$routerFormat = <<<'EOF'
<?php
$uri = $_SERVER['REQUEST_URI'];
$directory = '%s';
if (is_file($directory.'/'.$uri)) {
return false;
}
include $directory.'/%s';
EOF;
file_put_contents($routerFilename, sprintf($routerFormat.PHP_EOL, realpath($workingDirectory), $applicationFile));
$command = sprintf('%s -S %s:%d %s', PHP_BINARY, $host, $port, $routerFilename);
$process = proc_open(
$command,
[0 => $stdin, 1 => $stdout, 2 => $stderr],
$pipes,
$workingDirectory,
$_ENV
);
if (true === $background) {
posix_setsid();
exit(0);
}
$pid = proc_get_status($process)['pid'];
while (0 === pcntl_waitpid($pid, $status, WNOHANG | WUNTRACED)) {
sleep(2);
}
fwrite($stderr, 'HTTP server has stopped working'.PHP_EOL);
fclose($process);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment