php简易服务器代码示例


这是一个简单的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 Foundreturn 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查看效果。


上一篇:php简易服务器优缺点

下一篇:php文本过滤 如何防止 SQL注入


php
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器