同時安裝多個 PHP 版本


現在 PHP 其中一個很大的問題, 是很多個不同的 PHP 版本都有人使用, 對於開發者需要顧及程式碼是否可以在不同版本執行, 而對系統管理員, 就要面對不同程式可能需要不同 PHP 版本。

以下記錄一下在系統安裝不同 PHP 版本, 並可以按需要設定不同 Virtualhost 或目錄, 可以使用不同 PHP 版本的方法, 以下會以 CentOS 7 及 Apache 作為安裝環境。

首先在系統用 YUM 安裝好 Apache 及 PHP, 可以參考本站另一篇文章: RHEL 及 CentOS 7 安裝 Apache, MariaDB, PHP(LAMP)

上面安裝的 PHP 是 Redhat 7 預設的 PHP 5.4, 並透過 mod_php 執行。下面會安透過 mod_fcgid 執行不同 PHP 版本, 先安裝 mod_fcgid 及其他所需套件:

# yum install gcc libxml2-devel bzip2-devel zlib-devel \
curl-devel libmcrypt-devel libjpeg-devel \
libpng-devel gd-devel mysql-devel mod_fcgid

現在下載及編譯 PHP 源始碼, 以下會以 PHP 5.6 為例子:

# cd /usr/local/src
# wget http://hk1.php.net/get/php-5.6.29.tar.gz/from/this/mirror
# tar zxvf mirror
# cd php-5.6.29

以下是 PHP 編譯選擇

執行以下指令編譯:

# make
# make install
# mkdir /etc/php56
# cp php.ini-production /etc/php56/php.ini

開啟 PHP 5.6 的 php.ini:

# vi /etc/php56/php.ini

在最後的位置加入這行:

建立執行 PHP 5.6 的帳號及群組, 以下用 web1 作為例子:

# groupadd web1
# useradd -s /bin/false -d /var/www/web1 -m -g web1 web1
# chmod 755 /var/www/web1

然後建立儲存 html 的位置, 及設定 owner:

# mkdir -p /var/www/web1/html
# chown web1:web1 /var/www/web1/html

在一個 wrapper script 在 /var/www/php-fcgi-scripts

# mkdir -p /var/www/php-fcgi-scripts/web1
# vi /var/www/php-fcgi-scripts/web1/php-fcgi-starter

輸入以下內容:

儲存檔案後離開編輯器, 現在給 php-fcgi-starter 執行權限:

# chmod 755 /var/www/php-fcgi-scripts/web1/php-fcgi-starter
# chown -R web1:web1 /var/www/php-fcgi-scripts/web1

現在設定 Virtualhost, 開啟檔案 /etc/httpd/conf/httpd.conf:

# vi /etc/httpd/conf/httpd.conf

在檔案最後加上這段:

重新啟動 Apache:

# systemctl restart httpd

放一個簡單的 PHP 測試程式到 /var/www/web1/html:

# vi /var/www/web1/html/info.php

加入以下內容:

用瀏覽器查看, 應該看到預設 PHP 5.4 的 phpinfo 頁面。將同一個 info.php 放到 /var/www/web1/html/php56/ 目錄下, 應該會看到 PHP 5.6 的 phpinfo 頁面.

在 VirtualHost 部份如果沒有設定 FCGIWrapper, 會以預設的 PHP 5.4 執行, 要安裝其他 PHP 版本, 只要重覆以下編譯的步驟即可。

One Response

  1. Pingback: CentOS 7 安装 LMD 及 ClamAV | Mr.Cpp 02 November 2018
  2. jimmy 23 October 2020

Leave a Reply