雖然這段時間一直是在用 go 開發,但 PHP 對我的影響一直影響着我,語言只是一種工具,所用的場景一直都是由使用者來決定。雖然 PHP 沒有前幾年那么受歡迎,但它也在往前發展,變的越來越好。
在平時開發、測試時,往往需要本地啟動一些服務器,令我感覺非常方便的一個工具是 PHP 內置的一個服務器功能。通過命令行工具可以看得到使用方法:
➜ $ php --help
Usage: php [options] [-f] <file> [--] [args...]
php [options] -r <code> [--] [args...]
php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
php [options] -S <addr>:<port> [-t docroot] [router]
php [options] -- [args...]
php [options] -a
-a Run as interactive shell (requires readline extension)
-c <path>|<file> Look for php.ini file in this directory
-n No configuration (ini) files will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse and execute <file>.
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r <code> Run PHP <code> without using script tags <?..?>
-B <begin_code> Run PHP <begin_code> before processing input lines
-R <code> Run PHP <code> for every input line
-F <file> Parse and execute <file> for every input line
-E <end_code> Run PHP <end_code> after processing all input lines
-H Hide any passed arguments from external tools.
-S <addr>:<port> Run with built-in web server.
-t <docroot> Specify document root <docroot> for built-in web server.
-s Output HTML syntax highlighted source.
-v Version number
-w Output source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.
args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin
--ini Show configuration file names
...
根據說明,只需要簡單的使用命令 php -S 0.0.0.0:8001
就能在本地啟動一個 8001 端口的測試用的服務器,真的特別方便。
由於我本地的操作系統是 win10,但我同時也很喜歡 Linux 系統的開發環境,於是,也偶爾使用 win10 上的 wsl2 Ubuntu 20.04。接下來,我就簡單記錄一下如何在 Ubuntu 20.04 中安裝 php8.1。
安裝方式深度參考 如何在Ubuntu 20.04 上安裝 php8 ,如果你感興趣可以點擊查看。
作者在編寫《如何在Ubuntu 20.04 上安裝 php8》時,Ubuntu 20.04 默認的軟件庫已經自帶了 PHP7.4。要安裝 PHP8 需要基於 ondrej/php PPA 中安裝。
如果你給你生產環境安裝 PHP8 請確保你的應用支持 PHP8。
這篇文章介紹的 PHP8 安裝步驟也同樣適用於所有基於 Ubuntu 的發行版 Linux 系統。如: Kubuntu、Linux Mint 和 Elementary OS。
啟用軟件倉庫
Ondřej Surý 是一名 Debian 開發人員,他維護着一個包含多個 PHP 版本的倉庫。啟用 PPA 倉庫可以通過運行以下命令:
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
由於我本地並不需要 php-fpm 等組件,只需要 php8 cli 模塊,因此我省略其他部分,直討論 PHP8 cli 部分的安裝。
安裝 PHP8
由於在編寫本文時,PHP8.1 已經處於 RC 階段,而且軟件庫中也有 PHP8.1 了,因此我直接安裝 PHP8.1
sudo apt update
sudo apt install php8.1
等待安裝完成。此時你運行 php -v
已經可以看到 PHP 的版本信息,表示你已經成功安裝 PHP8.1。
如果需要試試啟動內置服務器的功能,可以運行 php -S 0.0.0.0:8001
,此時可以通過瀏覽器訪問 http://127.0.0.1:8001
,會得到一個 404 頁面。
通過這個測試服務器,你可以訪問 PHP 腳本頁面,也可以訪問一些靜態資源,用於開發會特別簡單、方便。