php实现 httpserver
PHP 实现 HTTP 服务器
PHP 可以通过内置的 cli-server 或手动编写 Socket 代码实现简单的 HTTP 服务器。以下是两种方法的实现方式:
使用 PHP 内置开发服务器
PHP 5.4+ 版本内置了开发服务器,适合本地测试:
php -S localhost:8000
启动后,服务器会监听 8000 端口,默认以当前目录为根目录。可通过 -t 指定文档根目录:
php -S localhost:8000 -t public/
手动实现 HTTP 服务器
通过 PHP 的 Socket 扩展手动实现一个基础的 HTTP 服务器:
<?php
$host = '127.0.0.1';
$port = 8080;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, $host, $port);
socket_listen($socket);
echo "Server running on http://{$host}:{$port}\n";
while (true) {
$client = socket_accept($socket);
$request = socket_read($client, 1024);
$response = "HTTP/1.1 200 OK\r\n";
$response .= "Content-Type: text/html\r\n\r\n";
$response .= "<h1>Hello from PHP HTTP Server!</h1>";
socket_write($client, $response);
socket_close($client);
}
保存为 server.php 并运行:
php server.php
进阶实现
以下代码支持静态文件处理和简单路由:
<?php
$host = '127.0.0.1';
$port = 8080;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, $host, $port);
socket_listen($socket);
echo "Server running on http://{$host}:{$port}\n";
$docRoot = __DIR__ . '/public';
while (true) {
$client = socket_accept($socket);
$request = socket_read($client, 4096);
if (preg_match('/GET \/(.*?) HTTP/', $request, $matches)) {
$path = $matches[1] ?: 'index.html';
$filePath = realpath("$docRoot/$path");
if ($filePath && is_file($filePath) && strpos($filePath, $docRoot) === 0) {
$content = file_get_contents($filePath);
$mime = mime_content_type($filePath);
$response = "HTTP/1.1 200 OK\r\n";
$response .= "Content-Type: {$mime}\r\n\r\n";
$response .= $content;
} else {
$response = "HTTP/1.1 404 Not Found\r\n\r\n";
$response .= "404 Not Found";
}
} else {
$response = "HTTP/1.1 400 Bad Request\r\n\r\n";
}
socket_write($client, $response);
socket_close($client);
}
注意事项
- 内置服务器仅用于开发环境,生产环境应使用 Nginx/Apache
- 手动实现的服务器缺少 HTTPS、并发处理等特性
- 对于高性能需求,可考虑使用 Swoole 扩展:
composer require swoole/swoole
然后使用 Swoole 的 HTTP 服务器组件:

$http = new Swoole\Http\Server("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/html");
$response->end("<h1>Hello Swoole</h1>");
});
$http->start();
以上方法可根据需求选择,从简单测试到生产级解决方案均可覆盖。






