溫馨提示×

php簡易服務器代碼示例

PHP
小樊
108
2024-12-12 12:16:52
欄目: 云計算

這是一個簡單的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查看效果。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女