Created
July 17, 2018 16:30
-
-
Save ezimuel/a2e0ff7308952f2aa946f828a1302a63 to your computer and use it in GitHub Desktop.
Swoole HTTP static file server example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
This example shows how to build a very simple web server for static files using only PHP + Swoole ext, no need of a web server such as nginx
.
Does it work with laravel symbolic link?
I run swoole with laravel with storage (a symbolic link), I got those:
[2021-06-11 10:06:58 *75.2] NOTICE finish (ERRNO 1005): session#4059 does not exists
[2021-06-11 10:06:58 *74.1] NOTICE finish (ERRNO 1005): session#4060 does not exists
@zx1986 you need to check if $staticFile
contains a valid path to your file (line 47).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why cannot be it implemented by Nginx rule?