How to Upgrade from PHP 7 to PHP 8 on an Ubuntu Cloud Server?

04-02-2024 02:36:52

This article demonstrates the process of upgrading PHP version from 7.x to 8.x on an Ubuntu 20.04 cloud server. Before initiating the upgrade, it is highly recommended to perform a comprehensive backup of your cloud server. In case any issues arise during the upgrade, the backup can be used to restore data, preventing irreversible faults and data loss.

Identifying Installed Components

Before upgrading the PHP version, it is essential to know the installed PHP 7.x components, as these will need to be upgraded to their corresponding PHP 8.x versions.

$ dpkg -l | grep php

Output:
php-common                                  install
php7.x-cli                                  install
php7.x-curl                                 install
[...]

Installing PHP 8 and Its Components

PHP 8.x might not be available in Ubuntu's default software repositories, thus necessitating the inclusion of a third-party repository. For this purpose, we use the ondrej/php repository.

$ sudo apt install software-properties-common
$ sudo add-apt-repository ppa:ondrej/php
$ sudo apt update
$ sudo apt install php8.0

Next, proceed to install common PHP components. This can be done based on the names of the components installed in the first step, upgrading them to their respective 8.x versions. Below are some commonly used PHP components.

$ sudo apt install php8.0-common php8.0-fpm php8.0-mysql php8.0-gmp php8.0-xml php8.0-xmlrpc php8.0-curl php8.0-mbstring php8.0-gd php8.0-dev php8.0-imap php8.0-opcache php8.0-readline php8.0-soap php8.0-zip php8.0-intl php8.0-cli libapache2-mod-php8.0

After the installation is complete, restart the PHP service.

$ sudo systemctl restart php8.0-fpm.service

Verify the PHP version.

$ php -v

Enabling PHP 8 in Apache

Apache's a2enmod and a2dismod scripts can be utilized to enable and disable components within Apache. Execute the following command, replacing 7.x with the actual version.

$ sudo a2dismod php7.x
$ sudo endismod php8.0
$ sudo systemctl restart apache2.service

Next, create a PHP test file named phpinfo.php in the website's root directory, with the following content.

<?php
phpinfo();

Access the file through a browser at: http://[IP address or domain]/phpinfo.php to verify that PHP has been upgraded to version 8.0. Upon successful verification, remove the test file.