在打开一个新的Lareval57项目的时候,发现在根目录下有一个server.php文件,
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <[email protected]>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
我猜想它应该是一个引导文件,好奇的想使用这个文件,发现怎么搞都不行,于是就搁置了。知道今天在《PHP之道》看到了PHP内置web服务器。
文档:https://www.php.net/features.commandline.webserver
PHP内置web服务器主要用于开发阶段的使用,它的原理就是将请求转发到指定php程序处理。
注意的点:
1、URI请求会被发送到PHP所在的的工作目录(Working Directory)进行处理,也就是当前目录;除非你使用了-t参数来自定义别的目录。
2、如果URI请求未指定执行哪个PHP文件,则默认执行目录内的index.php 或者 index.html。如果这两个文件都不存在,服务器会返回404错误。
意思就是说你的uri可以精确到具体文件,比如 http://localhost:8000/hello.php 或者只有参数 http://localhost:8000/info ,那么对于没有指定文件的会默认指定一个,比如
http://localhost:8000/index.php/info
3、如果启动时指定了一个PHP文件,则这个文件会作为一个“路由”脚本,意味着每次请求都会先执行这个脚本。如果这个脚本返回 FALSE ,那么直接返回请求的文件(例如请求静态文件不作任何处理)。否则会把输出返回到浏览器。一般会采用这种方式很灵活的嫁接到某个项目上。比如 laravel57的server.php文件。
示例1:
请求图片直接显示图片,请求HTML则显示“Welcome to PHP”
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"]))
return false; // 直接返回请求的文件
else {
echo "<p>Welcome to PHP</p>";
}
?>
php -S localhost:8000 router.php
实例2:
打印信息到命令行
<?php
// router.php
$uri = $_SERVER["REQUEST_URI"];
file_put_contents("php://stdout", "request: $uri\n");
echo "<p>Hello World</p>";
?>
php -S localhost:8000 router.php
访问:http://localhost:8000/info
命令行打印:request: /info
实例3:
就是上面的server.php文件
<?php
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// 增加一行日志
file_put_contents("php://stdout", "request: $uri\n");
// 路由的作用
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
?>
启动:php -S localhost:8000 server.php
访问:http://localhost:8000/info