Skip to content

Instantly share code, notes, and snippets.

@ezimuel
Created July 17, 2018 16:30
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ezimuel/a2e0ff7308952f2aa946f828a1302a63 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;
}
@iamcatodo
Copy link

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.

@zx1986
Copy link

zx1986 commented Jun 11, 2021

Does it work with laravel symbolic link?

@zx1986
Copy link

zx1986 commented Jun 11, 2021

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

@ezimuel
Copy link
Author

ezimuel commented Jun 11, 2021

@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