使用 PHP 內建的 web server 進行開發

開發 PHP 專案的時候常常會需要在機器上安裝 web server,例如 Nginx 或是 Apache。有些人貪圖方便也會直接安裝 XAMPP 之類全部打包好的安裝包。

不過,有時候功能簡單 PHP 內建 web server 用起來會更順手。

首先來個簡單的範例。

建立 index.php,並放在 public 資料夾下

<?php
echo "Now: " . date('Y-m-d H:i:s') . "\n";

專案資料夾長這樣。

.
└── public
    └── index.php

1 directory, 1 file

然後啟動 PHP 內建 web server。-S 是設定啟動 web server,並指定服務的 address 與 port;-t 則是指定網頁的根目錄。

php -S 0.0.0.0:8080 -t public/
[Tue Jun 28 01:52:47 2022] PHP 8.1.7 Development Server (http://0.0.0.0:8080) started

然後就可以 curl 或用瀏覽器打開看結果。

$ curl 'http://localhost:8080'
Now: 2022-06-27 17:53:40

這裡也用 Lumen 再測試一次。

首先建立 Lumen 專案。

$ composer create-project --prefer-dist laravel/lumen test
Creating a "laravel/lumen" project at "./test"
Installing laravel/lumen (v9.0.0)
  - Installing laravel/lumen (v9.0.0): Extracting archive
Created project in /Users/cqd/repo/test-d/test
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
Loading composer repositories with package information
Updating dependencies
Lock file operations: 107 installs, 0 updates, 0 removals
  - Locking brick/math (0.9.3)
(中略)
  - Locking webmozart/assert (1.11.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 107 installs, 0 updates, 0 removals
  - Installing doctrine/inflector (2.0.4): Extracting archive
(中略)
  - Installing phpunit/phpunit (9.5.21): Extracting archive
49 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating optimized autoload files
62 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

然後啟動 PHP 內建 web server。

$ cd test
$ php -S 0.0.0.0:8080 -t public/
[Tue Jun 28 01:57:24 2022] PHP 8.1.7 Development Server (http://0.0.0.0:8080) started

curl 過去,可以看到 Lumen 已經啟動。

$ curl  localhost:8080
Lumen (9.0.2) (Laravel Components ^9.0)