2022年12月15日 星期四

在CentOS上安裝PHP8

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. 下載穩定版的php8,解壓縮後,切到此目錄
cd /usr/src/
wget https://www.php.net/distributions/php-8.1.13.tar.gz
tar -xzvf php-8.1.13.tar.gz
cd php-8.1.13

4. 設定php編譯參數,如果有錯誤訊息,就要確認相依套件是否有安裝好
./configure --prefix=/usr/local/php \
--with-mysql-sock --with-mysqli --enable-fpm \
--enable-soap --with-openssl --with-mhash \
--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-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-8.1.13/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(/|$) {
    fastcgi_index index.php;
    fastcgi_pass 127.0.0.1:9000;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    root /usr/share/nginx/html;
}

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

12. 重新啟動nginx
systemctl restart nginx

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