Skip to content

Instantly share code, notes, and snippets.

@k-motoyan
Created November 22, 2015 15:41
Show Gist options
  • Save k-motoyan/d0da18e9e96ed3adf3c5 to your computer and use it in GitHub Desktop.
Save k-motoyan/d0da18e9e96ed3adf3c5 to your computer and use it in GitHub Desktop.
PHP standalone application server.
<?php
$server = stream_socket_server(
'tcp://127.0.0.1:8080',
$error_no,
$error_str,
STREAM_SERVER_LISTEN | STREAM_SERVER_BIND,
stream_context_create([
'socket' => [
'backlog' => 1024
]
])
);
$worker = 4;
$pids = [];
for ($i=0; $i<$worker; $i++) {
$pid = pcntl_fork();
if ($pid == -1) {
die('don\'t fork process.' . "\n");
} elseif($pid) {
$pids[] = $pid;
} else {
unset($pids);
break;
}
}
// master process.
if ($pids) {
while (true) {
foreach ($pids as $i => $pid) {
$res = pcntl_waitpid($pid, $status, WNOHANG);
if ($res == -1 || $res > 0) {
unset($pids[$i]);
}
}
sleep(1);
}
// child process.
} else {
while (true) {
if ($con = @stream_socket_accept($server)) {
$_ = fread($con, 8196);
ob_start();
include 'index.php';
$body = ob_get_clean();
$header = "HTTP/1.1 200 OK\n" .
"Content-Type: text/html; charset=UTF-8\n" .
"Content-Length: " . strlen($body) . "\n" .
"Connection: Close\n";
stream_socket_sendto($con, $header . "\n" . $body);
stream_socket_shutdown($con, STREAM_SHUT_RDWR);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment