Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Swoole HTTP static file server example
// Simple HTTP static file server using Swoole
$host = $argv[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)) {
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]);
return true;
Copy link

adamasantares commented May 3, 2020

Why cannot be it implemented by Nginx rule?

Copy link

iamcatodo commented May 3, 2020

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.

Copy link

zx1986 commented Jun 11, 2021

Does it work with laravel symbolic link?

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

Copy link

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