How to Install PHP on Ubuntu: A Complete Beginner-to-Advanced Guide (Ubuntu 22.04 LTS)

目次

1. Introduction

Why Use PHP on Ubuntu

PHP is a server-side scripting language widely used in many web applications, including WordPress. It has been used extensively in web development for many years, and a large number of CMS platforms and frameworks are built on PHP.

Ubuntu is a highly stable Linux distribution used by developers worldwide and is especially well suited for server environments. The combination of Ubuntu and PHP is widely adopted, from personal development setups to enterprise-grade production systems.

Target Audience and Purpose of This Article

This article is intended for a wide range of users, from beginners who want to install PHP on Ubuntu but are unsure where to start, to intermediate users who need to install specific PHP versions. The procedures are explained as clearly as possible.

The instructions are based on Ubuntu 22.04 LTS, but the same basic steps apply to other versions as well.

What You Will Learn

By reading this article, you will be able to understand and practice the following:

  • Basic methods for installing PHP on Ubuntu
  • How to install and switch between multiple PHP versions
  • How to verify PHP operation and troubleshoot issues
  • Configuration for Apache and Nginx integration
  • How to install commonly used PHP modules

2. Prerequisites and Preparation

How to Check Your Ubuntu Version

First, check which version of Ubuntu you are using. PHP installation methods and supported modules may vary slightly depending on the Ubuntu version.

You can check the Ubuntu version by running the following command:

lsb_release -a

Alternatively, you can use this command:

cat /etc/os-release

This article explains the procedures based on Ubuntu 22.04 LTS, but the same steps generally apply to Ubuntu 20.04 and 23.10.

Keep System Packages Up to Date

Before installing PHP, it is very important to update all system packages. This helps prevent dependency issues and conflicts.

sudo apt update
sudo apt upgrade -y

This updates the APT package index and ensures that all packages can be installed in their latest stable versions.

Install Required Utilities

Some PHP versions require additional tools for managing repositories. The package software-properties-common is needed to add repositories such as PPAs.

If it is not installed, install it using the following command:

sudo apt install -y software-properties-common

This package is required for commands like add-apt-repository, which are commonly used when installing specific PHP versions via a PPA.

Using Root Privileges or sudo

Most of the operations introduced in this article require system-level changes. Be sure to use sudo when running commands.

3. How to Install PHP

There are two main ways to install PHP on Ubuntu. One is installing from the default repositories, and the other is installing a specific version using a PPA (Personal Package Archive). Each method is explained in detail below.

Install PHP from the Default Repository

Ubuntu provides a stable version of PHP in its default repositories. If you do not need a specific version, this is the easiest method.

sudo apt install -y php

After installation, verify that PHP is installed correctly:

php -v

Example Output:

PHP 8.1.2 (cli) (built: ...)

On Ubuntu 22.04, PHP 8.1 is installed by default.

Install a Specific PHP Version Using a PPA

If you want to use the latest PHP version or manage multiple versions, you can add the ondrej/php PPA.

Step 1: Add the PPA Repository

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

This PPA is widely used in the Ubuntu community and provides stable builds for multiple PHP versions.

Step 2: Install the Desired PHP Version

For example, to install PHP 8.2:

sudo apt install -y php8.2

You can also install other versions such as PHP 7.4 or 8.0.

Step 3: Verify the Installed Version

php -v

4. Verifying PHP Operation

After installing PHP, verify that it works correctly. You can check this via the command line and through a web server such as Apache or Nginx.

Verify via Command Line (CLI)

First, check the PHP version from the terminal:

php -v

Example Output:

PHP 8.2.10 (cli) (built: Aug 23 2023 08:12:10) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.2.10, Copyright (c) Zend Technologies

Verify via Web Server (Apache)

If Apache is installed, create a test page using the phpinfo() function.

1. Create a Test File

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

2. Access via Browser

http://localhost/info.php

3. Confirm the Output

If detailed PHP information is displayed, PHP is working correctly with Apache.

🔍 Note: The phpinfo() output contains sensitive information. Delete the file after verification.

sudo rm /var/www/html/info.php

Verify with Nginx + PHP-FPM

When using Nginx, PHP is processed through php-fpm. To verify proper integration, ensure that .php files are correctly configured in the Nginx configuration file, then create an info.php file just as you would with Apache.

If the configuration is incorrect, you may encounter a 500 error or see the file downloaded instead of executed. In such cases, review settings such as fastcgi_pass and include fastcgi-php.conf; in the Nginx configuration.

5. Installing Commonly Used PHP Modules

Installing PHP alone does not provide all functionality. Many features are delivered as separate modules (extensions) that must be installed as needed. This section introduces commonly used PHP modules in real-world development and operations.

What Are PHP Modules?

PHP modules (also called extensions) add specific capabilities such as database connectivity, multibyte string handling, image processing, and XML parsing.

Modules are provided as APT packages and can be installed as follows:

sudo apt install php-module-name

If you want to specify a version, use a format such as php8.2-mbstring.

Major PHP Modules and Their Uses

php-mbstring (Multibyte String Support)

This module is essential for handling multibyte character strings such as Japanese text. It is almost mandatory for Japanese websites and email processing.

sudo apt install php-mbstring

php-mysql (MySQL / MariaDB Connectivity)

This module is required when connecting to databases such as MySQL or MariaDB. It is essential for applications like WordPress.

sudo apt install php-mysql

php-gd (Image Processing)

This module is used for generating, converting, and resizing images, and is commonly used for thumbnails and image manipulation.

sudo apt install php-gd

php-xml (XML Processing)

This module is required for handling XML-based data such as RSS feeds and SOAP services. It is commonly used in CMS platforms and API integrations.

sudo apt install php-xml

php-curl (HTTP Communication)

This module enables HTTP requests from the server, such as when integrating with external APIs. It is required by many modern frameworks.

sudo apt install php-curl

php-zip (Compressed File Handling)

This module allows you to create and extract ZIP files and is often used in file upload features.

sudo apt install php-zip

Enabling Modules and Restarting Services

Some modules require explicit activation after installation. Use phpenmod to enable them.

sudo phpenmod module_name
sudo systemctl restart apache2

The enabled modules take effect after restarting the web server.

6. Managing and Switching PHP Versions

Ubuntu allows you to install and use multiple PHP versions on a single server. This is especially useful in development environments or servers hosting multiple web applications.

This section explains how to switch PHP versions for the CLI and for Apache.

Switching PHP Versions in the CLI

Command Used: update-alternatives

You can easily switch the PHP version used in the command line using update-alternatives.

Step 1: Check Installed PHP Versions

ls /usr/bin/php*

Step 2: Register PHP Versions (First Time Only)

sudo update-alternatives --install /usr/bin/php php /usr/bin/php7.4 74
sudo update-alternatives --install /usr/bin/php php /usr/bin/php8.2 82

Step 3: Select the PHP Version

sudo update-alternatives --config php

You will see a selection menu similar to the following:

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:

Step 4: Verify the Version

php -v

Switching PHP Versions in Apache

When using Apache, PHP versions are managed via Apache modules. You can switch versions by enabling and disabling modules.

1. Check Available Modules

ls /etc/apache2/mods-available | grep php

2. Disable the Currently Active Module

sudo a2dismod php7.4

3. Enable the Desired Version

sudo a2enmod php8.2

4. Restart Apache

sudo systemctl restart apache2

7. Integrating PHP with Apache and Nginx

PHP becomes truly powerful when integrated with a web server. On Ubuntu, the most commonly used web servers are Apache and Nginx.

Apache Integration (mod_php)

Apache can process PHP scripts directly using the mod_php module. This method is simple and suitable for CMS platforms like WordPress.

Step 1: Install Apache and mod_php

sudo apt install -y apache2 libapache2-mod-php

Step 2: Restart Apache

sudo systemctl restart apache2

Step 3: Test PHP Execution

<?php
phpinfo();
?>
http://localhost/test.php

Nginx Integration (PHP-FPM)

Nginx does not process PHP directly. Instead, it relies on PHP-FPM (FastCGI Process Manager).

Step 1: Install Nginx and PHP-FPM

sudo apt install -y nginx php-fpm

Step 2: Edit the Nginx Configuration

sudo nano /etc/nginx/sites-available/default
location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

Step 3: Restart Nginx

sudo systemctl restart nginx

8. Troubleshooting

PHP Source Code Is Displayed in the Browser

Cause

This occurs when the web server does not process PHP files correctly.

Solution

  • Apache:
sudo apt install libapache2-mod-php
sudo systemctl restart apache2
  • Nginx:
sudo systemctl restart php8.2-fpm
sudo systemctl restart nginx

PHP Functions Are Undefined

Cause

Required PHP modules are not installed or enabled.

Solution

sudo apt install php-mbstring php-xml php-curl
sudo systemctl restart apache2
php -m

PHP Errors Are Not Displayed

Solution

sudo nano /etc/php/8.2/apache2/php.ini
display_errors = On
error_reporting = E_ALL
sudo systemctl restart apache2

Log File Locations

Apache:

/var/log/apache2/error.log

Nginx:

/var/log/nginx/error.log

PHP-FPM:

/var/log/php8.2-fpm.log

9. Summary

This article provided a step-by-step explanation of how to install PHP on Ubuntu, from basics to advanced topics.

Key Takeaways

  • Check your Ubuntu version and update packages
  • Install PHP via default repositories or PPAs
  • Verify PHP via CLI and web servers
  • Extend functionality with modules
  • Manage multiple PHP versions flexibly
  • Integrate properly with Apache or Nginx
  • Check logs when troubleshooting

Next Steps

  • Install MySQL or MariaDB
  • Set up WordPress
  • Use PHP frameworks like Laravel
  • Enable HTTPS with SSL certificates
  • Manage services with systemd

Ubuntu and PHP together provide a robust and flexible development environment. Use this guide as a foundation and continue expanding your skills.

10. Frequently Asked Questions (FAQ)

Q1. How do I install the latest PHP version on Ubuntu?

A. Use the ondrej/php PPA and specify the desired version.

Q2. How do I switch PHP versions in the CLI?

sudo update-alternatives --config php

Q3. PHP source code is displayed in Apache.

sudo apt install libapache2-mod-php
sudo systemctl restart apache2

Q4. Where is php.ini located?

  • Apache: /etc/php/8.2/apache2/php.ini
  • CLI: /etc/php/8.2/cli/php.ini

Q5. How do I enable PHP modules?

sudo phpenmod mbstring
sudo systemctl restart apache2

Q6. PHP does not work with Nginx.

Ensure that php-fpm is installed and fastcgi_pass is correctly configured.

Q7. PHP errors are not visible.

display_errors = On
error_reporting = E_ALL