ceacer 2 已发布 2月3号 分享 已发布 2月3号 这是一个简单的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查看效果。 评论链接 在其他网站上分享 更多分享选项...
推荐帖
创建账户或登录以发表评论
您需要成为会员才能发表评论
创建一个帐户
在我们的社区注册一个新账户。很简单!
注册新账户登入
已有账户?在此登录
立即登录