search
HomeBackend DevelopmentPHP Tutorial[Modern PHP] 第二章 新特性之七 内置HTTP服务器

内置HTTP服务器


你知道PHP从5.4.0开始有了一个内置的web服务器吗?对于那些只知道使用Apache或者nginx去预览PHP页面的PHP开发者们来说这又是一块未被发掘的宝石。虽然你不能在产品环境中使用PHP的内置web服务器,但是这个功能对于本地开发来说真是的一个完美的工具。


无论我是否在写PHP代码,反正每天都会使用PHP的内置web服务器。我会使用它来预览Laravel和Slim Framework(译者注:框架的作者就是本书的作者Josh Lockhart)应用程序,在使用Drupal框架的内容管理系统搭建网站时也会使用它,甚至在构造原型页面时使用它来预览静态的HTML和CSS。


记住,PHP内置的服务器是一个web服务器。它只使用HTTP协议,除了PHP文件之外,它还可以返回静态资源。我们可以在不使用MAMP、WAMP或者其它重量级的web服务器的情况下在本地很好的完成HTML页面的开发和预览操作。


启动服务器


启动PHP的web服务器很简单。打开你的终端程序,进入你的项目的文档根目录并执行下面的命令:

php -S localhost:4000


这个命令可以启动一个新的PHP web服务器,我们通过localhost就可以访问这个服务器。它会监听4000端口。而你当前的工作目录就是web服务器的文档根目录。


打开浏览器访问 http://localhost:4000 就可以预览你的应用程序了。由于你使用web浏览器浏览自己的应用程序,每个HTTP请求都会在你的终端程序中记录并直接在终端输出出来,通过它可以检测到你的应用程序是否会出现400或者500错误。


有时候你会需要允许其他的设备来访问你本地环境中的PHP web服务器(例如使用你的iPad或者本地的Windows虚拟机进行预览)。要实现这个需求,你可以让PHP web服务器使用0.0.0.0代替localhost来监听来自所有网络连接的请求。

php -S 0.0.0.0:4000


当你准备停止PHP web服务器时,直接关闭终端程序或者按Ctrl+C就可以了。


配置服务器


一个应用程序对应一个PHP的INI配置文件是很常用的处理,尤其是你的应用程序对内存使用、文件上传、调试或者字节码缓存等有着特别的需求。使用PHP内置服务器时我们可以使用-c参数告诉服务器去使用某个指定的INI文件:

php -S localhost:8000 -c app/config/php.ini


把自定义的INI文件放到应用程序的根目录下是很好的主意,甚至可以使用版本控制来保存INI文件,以便与开发团队中的其他开发者们进行共享。


路由脚本


不同于Apache或者nginx,PHP内置服务器有个明显的缺陷:它不支持.htaccess文件。因此很多流行的PHP框架都使用的前端控制器在PHP内置服务器上用起来却很麻烦。


前端控制器是一个单独的PHP文件,所有的HTTP请求都被转发到它上面(通过.htaccess文件或者rewrite规则)。前端控制器文件负责将请求进行路由并分发到对应的PHP代码上。Symfony和其他流行的PHP框架都使用了这个常用的模式。


PHP内置服务器使用路由脚本可以稍微弥补这个缺陷。路由脚本会在每次HTTP请求之前被执行。如果脚本返回false,那么会直接返回当前HTTP请求地址对应的静态资源,反之,则将脚本返回的内容作为HTTP返回内容返回给浏览器。换句话说,你的路由脚本事实上就是在照搬.htaccess文件的功能。


使用路由脚本很简单,只需要将PHP脚本的文件地址作为一个桉树传递给PHP内置服务器的启动命令:

php -S localhost:8000 router.php


判断来自内置服务器的请求


有时候能够区分访问的PHP脚本是来自PHP内置服务器还是类似Apache和nginx的传统的web服务器是很有用的。或许你需要在nginx中添加一个专门的HTTP头(例如 Status:)但是在PHP web服务器上却坐不到。你可以通过php_sapi_name()函数来判断出PHP web server。当你当前请求的脚本是来自PHP内置服务器时这个函数会返回字符串 cli-server:

<?phpif (php_sapi_name() === 'cil-server') {    // PHP内置web服务器} else {    // 其它web服务器}

缺点


PHP内置web服务器不可以在产品环境中使用。它仅仅是为了本地开发设计。如果你在产品服务器上使用了PHP内置服务器,你将面对的是大量失望的用户以及来自Pingdom的洪水般的当机通知。


  • 内置服务器之所以性能不佳是因为它每次只能处理一个请求,而其他的请求都会被block住。如果一个PHP文件被卡在了慢查询或者远程的API返回上,那你的web应用就无法响应了。
  • 内置服务器只支持有限的MIME类型
  • 内置服务器使用路由脚本限制了URL rewriting。你需要Apache或者nginx来实现更高级的URL rewriting操作
  • Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

    APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

    Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

    Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

    PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

    PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

    PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

    PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

    How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

    TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

    PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

    ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

    PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

    Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

    PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

    DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),