Install PHP 8.1 on Ubuntu 20.04

PHP is a programming language which often used for creating a web applications and dynamic websites. A new features and various changes are introduced on each release of PHP.

This tutorial demonstrates how to install PHP 8.1 on Ubuntu 20.04.

Install PHP

Add PHP repository:

sudo add-apt-repository -y ppa:ondrej/php

Run the following command to install PHP 8.1 with command line interface (CLI):

sudo apt install -y php8.1-common php8.1-cli

When installation is completed, we can check PHP version:

php --version

PHP has various extensions which provides additional functionality. We can install PHP extensions using the following syntax:

sudo apt install -y php8.1-extension_name

Run the following command to install commonly used PHP extensions:

sudo apt install -y php8.1-curl php8.1-gd php8.1-mbstring php8.1-xml php8.1-zip

The -m option allows to check which extensions are currently installed.

php -m

PHP integration with MySQL or MariaDB

If you want to use PHP with MySQL or MariaDB database, install the following extension:

sudo apt install -y php8.1-mysql

PHP integration with Apache

If you want to integrate PHP with Apache HTTP server, install the following extension:

sudo apt install -y libapache2-mod-php8.1

When it finished, restart Apache:

sudo service apache2 restart

Testing PHP

Create a new main.php file:

nano main.php

Once file is opened, add the following lines of code:


echo 'Hello world';

Execute command to test a script:

php main.php

Uninstall PHP

If you want to completely remove PHP and related dependencies, run the following command:

sudo apt purge --autoremove -y php-common

Remove GPG key and repository:

sudo rm -rf /etc/apt/trusted.gpg.d/ondrej_ubuntu_php.gpg
sudo rm -rf /etc/apt/sources.list.d/ondrej-ubuntu-php-focal.list

Remove PHP related file:

sudo rm -rf /var/lib/systemd/timers/stamp-phpsessionclean.timer

Leave a Comment

Your email address will not be published. Required fields are marked *