現在 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 及其他所需套件:
curl-devel libmcrypt-devel libjpeg-devel \
libpng-devel gd-devel mysql-devel mod_fcgid
現在下載及編譯 PHP 源始碼, 以下會以 PHP 5.6 為例子:
# wget http://hk1.php.net/get/php-5.6.29.tar.gz/from/this/mirror
# tar zxvf mirror
# cd php-5.6.29
以下是 PHP 編譯選擇
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
./configure --prefix=/usr/local/php56 \ --with-config-file-path=/etc/php56 \ --with-config-file-scan-dir=/etc/php56/php.d \ --with-libdir=lib64 \ --with-mysql \ --with-mysqli \ --enable-mbstring \ --disable-debug \ --disable-rpath \ --with-bz2 \ --with-curl \ --with-gettext \ --with-iconv \ --with-openssl \ --with-gd \ --with-mcrypt \ --with-pcre-regex \ --with-zlib \ --enable-cgi |
執行以下指令編譯:
# make install
# mkdir /etc/php56
# cp php.ini-production /etc/php56/php.ini
開啟 PHP 5.6 的 php.ini:
在最後的位置加入這行:
1 |
cgi.fix_pathinfo = 1 |
建立執行 PHP 5.6 的帳號及群組, 以下用 web1 作為例子:
# useradd -s /bin/false -d /var/www/web1 -m -g web1 web1
# chmod 755 /var/www/web1
然後建立儲存 html 的位置, 及設定 owner:
# chown web1:web1 /var/www/web1/html
在一個 wrapper script 在 /var/www/php-fcgi-scripts
# vi /var/www/php-fcgi-scripts/web1/php-fcgi-starter
輸入以下內容:
1 2 3 4 5 6 |
#!/bin/sh PHPRC=/etc/ export PHPRC export PHP_FCGI_MAX_REQUESTS=5000 export PHP_FCGI_CHILDREN=8 exec /usr/local/php56/bin/php-cgi |
儲存檔案後離開編輯器, 現在給 php-fcgi-starter 執行權限:
# chown -R web1:web1 /var/www/php-fcgi-scripts/web1
現在設定 Virtualhost, 開啟檔案 /etc/httpd/conf/httpd.conf:
在檔案最後加上這段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<VirtualHost *:80> ServerName web1.example.com DocumentRoot /var/www/web1/html/ <IfModule mod_fcgid.c> SuexecUserGroup web1 web1 <Directory /var/www/web1/html/> Options +ExecCGI AllowOverride All Order allow,deny Allow from all </Directory> </IfModule> </VirtualHost> <Directory /var/www/web1/html/php56> <FilesMatch \.php$> SetHandler None ForceType text/plain </FilesMatch> <FilesMatch \.phps$> SetHandler application/x-httpd-php-source </FilesMatch> AddHandler fcgid-script .php FCGIWrapper /var/www/php-fcgi-scripts/web1/php-fcgi-starter .php </Directory> |
重新啟動 Apache:
放一個簡單的 PHP 測試程式到 /var/www/web1/html:
加入以下內容:
1 2 3 |
<?php phpinfo(); ?> |
用瀏覽器查看, 應該看到預設 PHP 5.4 的 phpinfo 頁面。將同一個 info.php 放到 /var/www/web1/html/php56/ 目錄下, 應該會看到 PHP 5.6 的 phpinfo 頁面.
在 VirtualHost 部份如果沒有設定 FCGIWrapper, 會以預設的 PHP 5.4 執行, 要安裝其他 PHP 版本, 只要重覆以下編譯的步驟即可。
您好, 請問要如何切換2個站台, 我試著用網址好像不行.., 也可以正常啟用, 現在變成 /var/www/web1/html/php56/ 加一個info.php , 變成是PHP5.4的資訊, 🙁