Ubuntu 透過 ppa:ondrej/php 安裝新版本的 PHP

Ubuntu 如果不是最新版,sudo apt install php 所安裝的 PHP 版本通常比較舊(Ex: 20.04 會安裝 PHP 7.4)。

如果想要安裝比較新版本的 PHP,又不想自己 compile,通常會透過 ppa:ondrej/php 來安裝。

首先安裝需要的憑證:

sudo apt install ca-certificates apt-transport-https software-properties-common

一些很舊的教學會需要手動匯入憑證,這年頭應該是不用這麼麻煩了...

然後把 Ondřej Surý 義務維護(請抱持感恩的心)的 PPA 加進系統裡面:

sudo add-apt-repository ppa:ondrej/php

最後更新 apt 套件資料庫,就可以安裝了更新版本的 PHP 了。

$ sudo apt update
Hit:1 https://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 https://download.docker.com/linux/ubuntu focal InRelease
Hit:3 http://tw.archive.ubuntu.com/ubuntu focal InRelease
Hit:4 http://tw.archive.ubuntu.com/ubuntu focal-updates InRelease
Hit:5 http://tw.archive.ubuntu.com/ubuntu focal-backports InRelease
Hit:6 http://security.ubuntu.com/ubuntu focal-security InRelease
Hit:7 http://ppa.launchpad.net/ondrej/php/ubuntu focal InRelease
Hit:8 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Reading package lists... Done
Building dependency tree
Reading state information... Done
7 packages can be upgraded. Run 'apt list --upgradable' to see them.

$ sudo apt install php8.1 -y
[以下省略]

最後可以用 php -v 來驗證安裝的版本正確

$ php -v
PHP 8.1.9 (cli) (built: Aug 15 2022 09:39:52) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.9, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.9, Copyright (c), by Zend Technologies