php内置服务器使用方法

1 启动Web服务器

  1. $ cd ~/public_html
  2. $ php -S localhost:8000

终端输出信息:

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

当请求了 http://localhost:8000/http://localhost:8000/myscript.html 地址后,终端输出类似如下的信息:

  1. PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
  2. Listening on localhost:8000
  3. Document root is /home/me/public_html
  4. Press Ctrl-C to quit.
  5. [Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read
  6. [Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read
  7. [Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read
  8. [Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read
  9. [Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read

2 启动web服务器时指定文档的根目录

  1. $ cd ~/public_html
  2. $ php -S localhost:8000 -t foo/

终端显示信息:

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

如果你在启动命令行后面附加一个php脚本文件,那这个文件将会被当成一个“路由器”脚本。这个脚本将负责所有的HTTP请求,如果这个脚本执行时返回FALSE,则被请求的资源会正常的返回。如果不是FALSE,浏览里显示的将会是这个脚本产生的内容。

3 使用路由器脚本

在这个例子中,对图片的请求会返回相应的图片,但对HTML文件的请求会显示“Welcome to PHP”:

  1. <?php
  2. // router.php
  3. if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
  4. return false; // serve the requested resource as-is.
  5. } else {
  6. echo "<p>Welcome to PHP</p>";
  7. }
  8. ?>

执行:

  1. $ php -S localhost:8000 router.php

4 判断是否是在使用内置web服务器

通过程序判断来调整同一个PHP路由器脚本在内置Web服务器中和在生产服务器中的不同行为:

  1. <?php
  2. // router.php
  3. if (php_sapi_name() == 'cli-server') {
  4. /* route static assets and return false */
  5. }
  6. /* go on with normal index.php operations */
  7. ?>

执行:

  1. $ php -S localhost:8000 router.php

这个内置的web服务器能识别一些标准的MIME类型资源,它们的扩展有:.css, .gif, .htm, .html, .jpe, .jpeg, .jpg, .js, .png, .svg, and .txt。对.htm 和 .svg 扩展到支持是在PHP 5.4.4之后才支持的。

5 处理不支持的文件类型

如果你希望这个Web服务器能够正确的处理不被支持的MIME文件类型,这样做:

  1. <?php
  2. // router.php
  3. $path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
  4. if ($path["extension"] == "ogg") {
  5. header("Content-Type: video/ogg");
  6. readfile($_SERVER["SCRIPT_FILENAME"]);
  7. }
  8. else {
  9. return FALSE;
  10. }
  11. ?>

执行:

  1. $ php -S localhost:8000 router.php

如果你希望能远程的访问这个内置的web服务器,你的启动命令需要改成下面这样:

6 远程访问这个内置Web服务器

  1. $ php -S 0.0.0.0:8000

这样你就可以通过 8000 端口远程的访问这个内置的web服务器了。

文章不错, 赏你二两银子

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续努力!