Skip to content

Commit 08edbcc

Browse files
committed
Add script to server built-in webserver
1 parent e266e04 commit 08edbcc

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

script/server

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env php
2+
<?php
3+
4+
/**
5+
* Parse CLI options and start the built-in development server.
6+
*/
7+
function server($argv)
8+
{
9+
$host = 'localhost';
10+
$port = 3000;
11+
12+
$args = array_slice($argv, 1);
13+
for ($i = 0; $i < count($args); $i++) {
14+
$arg = $args[$i];
15+
if ($arg == '--help') {
16+
echo "Usage: ./script/server [options]\n";
17+
echo " -h HOST, --host=HOST Bind to HOST (default: localhost)\n";
18+
echo " -p PORT, --port=PORT Bind to PORT (default: 3000)\n";
19+
exit(0);
20+
} elseif ($arg == '-p' && isset($args[$i + 1])) {
21+
$port = (int)$args[++$i];
22+
} elseif (preg_match('/^--port=(\d+)$/', $arg, $m)) {
23+
$port = (int)$m[1];
24+
} elseif ($arg == '-h' && isset($args[$i + 1])) {
25+
$host = $args[++$i];
26+
} elseif (preg_match('/^--host=(.+)$/', $arg, $m)) {
27+
$host = $m[1];
28+
} else {
29+
echo "Unknown option: $arg\n";
30+
echo "Try ./script/server --help\n";
31+
exit(1);
32+
}
33+
}
34+
35+
$docroot = dirname(__DIR__) . '/public';
36+
37+
pcntl_exec(PHP_BINARY, array('-S', "$host:$port", '-t', $docroot, __FILE__));
38+
}
39+
40+
/**
41+
* Router required by PHP's built-in webserver. Serves static files
42+
* directly or routes everything else through the front controller.
43+
*/
44+
function router()
45+
{
46+
$docroot = $_SERVER['DOCUMENT_ROOT'];
47+
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
48+
$file = $docroot . $path;
49+
50+
if (file_exists($file) && is_file($file)) {
51+
return false;
52+
}
53+
54+
require_once $docroot . '/index.php';
55+
}
56+
57+
if (php_sapi_name() == 'cli-server') {
58+
return router();
59+
} else {
60+
server($argv);
61+
}

0 commit comments

Comments
 (0)