Skip to content

Instantly share code, notes, and snippets.

@nezamy
Forked from ezimuel/static.php
Created June 5, 2020 23:07
Show Gist options
  • Save nezamy/53512b03a2460a44a097abb01cc61240 to your computer and use it in GitHub Desktop.
Save nezamy/53512b03a2460a44a097abb01cc61240 to your computer and use it in GitHub Desktop.
Swoole HTTP static file server example
<?php
// Simple HTTP static file server using Swoole
$host = $argv[1] ?? '127.0.0.1';
$port = $argv[2] ?? 9501;
$http = new swoole_http_server($host, $port);
// The usage of enable_static_handler seems to produce errors
// $http->set([
// 'document_root' => __DIR__,
// 'enable_static_handler' => true
// ]);
$http->on("start", function ($server) {
printf("HTTP server started at %s:%s\n", $server->host, $server->port);
printf("Master PID: %d\n", $server->master_pid);
printf("Manager PID: %d\n", $server->manager_pid);
});
$static = [
'css' => 'text/css',
'js' => 'text/javascript',
'png' => 'image/png',
'gif' => 'image/gif',
'jpg' => 'image/jpg',
'jpeg' => 'image/jpg',
'mp4' => 'video/mp4'
];
$http->on("request", function ($request, $response) use ($static) {
if (getStaticFile($request, $response, $static)) {
return;
}
$response->status(404);
$response->end();
});
$http->start();
function getStaticFile(
swoole_http_request $request,
swoole_http_response $response,
array $static
) : bool {
$staticFile = __DIR__ . $request->server['request_uri'];
if (! file_exists($staticFile)) {
return false;
}
$type = pathinfo($staticFile, PATHINFO_EXTENSION);
if (! isset($static[$type])) {
return false;
}
$response->header('Content-Type', $static[$type]);
$response->sendfile($staticFile);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment