在 Ubuntu 上切换 PHP 版本,常见做法有两种:使用 update-alternatives(CLI) 和 针对 Web 服务(Apache / Nginx)切换 PHP-FPM 或模块。下面按场景给你完整说明。
先确认系统里有哪些 PHP 版本:
ls /usr/bin/php*
或:
update-alternatives --list php
如果没有你需要的版本,先安装,例如:
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
# 安装 PHP 7.4 和 PHP 8.2
sudo apt install php7.4 php8.2
sudo update-alternatives --config php
输出示例:
There are 2 choices for the alternative php (providing /usr/bin/php).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/php8.2 82 auto mode
1 /usr/bin/php7.4 74 manual mode
2 /usr/bin/php8.2 82 manual mode
Press <enter> to keep the current choice[*], or type selection number:
输入数字并回车即可。
验证:
php -v
sudo update-alternatives --set php /usr/bin/php7.4
sudo a2dismod php8.2
sudo a2enmod php7.4
sudo systemctl restart apache2
✅ 适合 libapache2-mod-php 模式
ls /run/php/
常见:
php7.4-fpm.sock
php8.2-fpm.sock
编辑站点配置(如 /etc/nginx/sites-available/default):
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
sudo systemctl restart php8.2-fpm
sudo systemctl restart php7.4-fpm
sudo systemctl restart nginx
✅ Nginx 必须和 PHP-FPM 版本一致
update-alternativesphp-fpmfastcgi_passphp -v 没变?hash -r如果你愿意,可以直接告诉我:
我可以给你 精确到命令级别 的操作方案。