2023年2月16日 星期四

在CentOS上安裝PHP7.4

1. 先安裝一下epel-release
yum -y install epel-release

2. 在安裝php會用到的函示庫,執行以下指令
yum install -y \
gcc-c++ autoconf libjpeg libjpeg-devel libpng \
libpng-devel freetype freetype-devel \
libpng libpng-devel libxml2 libxml2-devel \
zlib zlib-devel glibc glibc-devel glib2 \
glib2-devel bzip2 bzip2-devel ncurses curl \
openssl-devel gdbm-devel db4-devel libXpm-devel \
libX11-devel gd-devel gmp-devel readline-devel \
libxslt-devel expat-devel xmlrpc-c xmlrpc-c-devel \
libicu-devel libmcrypt-devel libmemcached-devel \
sqlite-devel oniguruma-devel

3. 下載穩定版的php7,解壓縮後,切到此目錄
cd /usr/src/
wget http://tw2.php.net/distributions/php-7.4.33.tar.gz
tar -xzvf php-7.4.33.tar.gz
cd php-7.4.33

4. 設定php編譯參數,如果有錯誤訊息,就要確認相依套件是否有安裝好
./configure --prefix=/usr/local/php \
--with-mysql-sock --with-mysqli --enable-fpm \
--enable-soap --with-openssl --with-mhash \
--enable-inline-optimization --with-zlib --enable-bcmath \
--with-iconv --with-bz2 --enable-calendar \
--with-curl --with-cdb --enable-dom \
--enable-exif --enable-fileinfo --enable-filter \
--enable-ftp --with-openssl-dir --with-zlib-dir \
--enable-gd-jis-conv --with-gettext --with-gmp \
--enable-json --enable-mbstring --enable-mbregex \
--disable-debug --enable-pdo --with-pdo-mysql \
--with-readline --enable-session --enable-shmop \
--enable-simplexml --enable-sockets --enable-sysvmsg \
--enable-sysvsem --enable-sysvshm --with-xsl \
--disable-rpath --with-pear --enable-intl \
--enable-mysqlnd-compression-support

5. 進行編譯跟安裝
make
make install

6. 執行以下建立php的環境變數
ln -sf /usr/local/php/bin/php /usr/local/bin/php

7. 執行以下步驟,將預設的配置檔複製到正常路徑
cp php.ini-development /usr/local/php/lib/php.ini
cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf
cp /usr/src/php-7.4.33/sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm

8. 啟動php-fpm
/etc/init.d/php-fpm restart
/etc/init.d/php-fpm start

9. 修改php.ini,把cgi.fix_pathinfo=0 (為了安全性,避免惡意腳本插入攻擊)
vim /usr/local/php/lib/php.ini

10. 打開nginx的設定檔,加入PHP的設定,執行 vim /etc/nginx/conf.d/default.conf 在index部分加入 index.php 加入以下設定
location / {
    root /usr/share/nginx/html;
    index index.php index.html index.htm;
}
location  ~ \.php(/|$) {
    root /usr/share/nginx/html;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

11. 在跟目錄就可以新增一個php檔案來測試,編輯vim /usr/share/nginx/html/info.php
<?php
    phpinfo();
?>

12. 重新啟動nginx
systemctl restart nginx

13. 打開網址http://xx.xx.xx.xx/info.php