這是一個簡單的PHP內置HTTP服務器代碼示例,它可以在本地環境中快速搭建一個簡單的Web服務器。請注意,這個服務器僅適用于開發和測試目的,不建議在生產環境中使用。
<?php
// 設置監聽端口
$port = 8080;
// 設置根目錄
$root_dir = 'public';
// 檢查是否安裝了必要的擴展
if (!extension_loaded('http_server')) {
die("請確保已安裝http_server擴展");
}
// 創建一個HTTP服務器
$server = new HttpServer($root_dir, function (Psr\Http\Message\ServerRequestInterface $request) {
// 獲取請求的URI
$uri = $request->getUri();
// 根據URI路由到相應的文件或處理邏輯
switch ($uri) {
case '/':
// 返回index.html文件
return new Psr\Http\Message\Response(
200,
['Content-Type' => 'text/html'],
file_get_contents($root_dir . '/index.html')
);
case '/css/style.css':
// 返回CSS文件
return new Psr\Http\Message\Response(
200,
['Content-Type' => 'text/css'],
file_get_contents($root_dir . '/css/style.css')
);
default:
// 如果請求的URI不存在,返回404 Not Found
return new Psr\Http\Message\Response(
404,
['Content-Type' => 'text/plain'],
"File not found: {$uri}"
);
}
});
// 啟動服務器并監聽指定端口
$server->listen($port);
echo "Server is running at http://localhost:{$port}\n";
將上述代碼保存為server.php文件,然后在命令行中運行php server.php。這將啟動一個簡單的HTTP服務器,監聽8080端口。你可以在瀏覽器中訪問http://localhost:8080查看效果。