PHP cli-server 在php5.4起内置的web服务器,主要用于本地开发使用,不可用于线上产品环境。

启动web服务器

cd ~/public_html
php -S localhost:8000

终端窗口会显示:

text
PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit

启动时指定根目录

cd ~/publich_html
php -S localhost:8000 -t foo/

终端窗口会显示:

text
PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011
Listening on localhost:8000
Document root is /home/me/public_html/foo
Press Ctrl-C to quit

使用路由(Router)脚本

请求图片直接显示图片,请求HTML则显示“Welcome to PHP”

router.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

实现跨域

以Yii为例,
web/index.php


$CORS_ORIGIN_ALLOWED = "http://localhost:8080";
function consoleLog($level, $msg) {
file_put_contents("php://stdout", "[" . $level . "] " . $msg . "\n");
}
function applyCorsHeaders($origin) {
consoleLog('info', "Transparent routing for : " . $_SERVER["REQUEST_URI"]);

header("Access-Control-Allow-Origin: $origin");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

}
if(isset($_SERVER["HTTP_ORIGIN"])){
// applyCorsHeaders($CORS_ORIGIN_ALLOWED);
applyCorsHeaders($_SERVER['HTTP_ORIGIN']);
}

require __DIR__ . '/../vendor/autoload.php';
...

运行

php -S localhost:8000 -t web index.php