php 实现webserver
PHP 实现简易 Web 服务器
PHP 内置了一个简易的 Web 服务器,适合开发环境使用。以下方法基于 PHP 5.4+ 版本。
启动内置服务器
php -S localhost:8000
默认监听 8000 端口,根目录为当前命令行所在路径。访问 http://localhost:8000 即可。
指定根目录
php -S localhost:8000 -t /path/to/root
-t 参数指定文档根目录。
路由处理
创建 router.php 文件实现自定义路由:
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false; // 直接返回静态文件
} else {
include __DIR__ . '/index.php'; // 其他请求交给前端控制器
}
启动时指定路由文件:

php -S localhost:8000 router.php
使用 PHP 实现完整 Web 服务器
基于 socket 的实现
$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 at 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 World</h1>";
socket_write($client, $response);
socket_close($client);
}
处理请求 扩展上述代码可解析 HTTP 请求:
$requestLines = explode("\n", $request);
$requestLine = $requestLines[0];
list($method, $path, $protocol) = explode(' ', $requestLine);
返回文件内容
$filePath = __DIR__ . $path;
if (file_exists($filePath)) {
$content = file_get_contents($filePath);
$response = "HTTP/1.1 200 OK\r\n";
$response .= "Content-Type: text/html\r\n\r\n";
$response .= $content;
} else {
$response = "HTTP/1.1 404 Not Found\r\n\r\n";
}
生产环境注意事项
内置服务器仅适合开发环境。生产环境应使用:

- Apache + mod_php
- Nginx + PHP-FPM
- OpenLiteSpeed
性能优化建议:
- 启用 OPcache
- 使用 PHP 7.4+ 或 8.x 版本
- 配置适当的 worker 进程数
安全配置
限制访问
php -S 0.0.0.0:8000
监听所有网络接口时需配置防火墙。
HTTPS 支持 内置服务器不支持 HTTPS,可通过反向代理实现:
- Nginx 配置 SSL 终止
- 使用 Cloudflare 等 CDN
禁用危险函数
在 php.ini 中禁用:
disable_functions = "exec,passthru,shell_exec,system"
以上方法提供了从简单到复杂的 PHP Web 服务器实现方案,可根据实际需求选择适合的方式。





