How to Install and Use PHP on Ubuntu: Complete Beginner’s Guide for 2025

目次

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 a standard in web development for many years, powering numerous CMSs and frameworks.

Ubuntu is a highly stable Linux distribution favored by developers worldwide and is especially well-suited for server use. The combination of Ubuntu and PHP is widely adopted, from personal projects to enterprise production environments.

Who This Article Is For & Its Purpose

This guide is for everyone from beginners—who want to install PHP on Ubuntu but aren’t sure where to start—to intermediate users who want to install a specific PHP version. We provide clear, step-by-step instructions.

We use Ubuntu 22.04 LTS as the example environment, but the steps are generally similar for other versions as well.

What You’ll Learn in This Article

By reading this guide, you’ll be able to understand and perform the following tasks:

  • Basic methods for installing PHP on Ubuntu
  • How to install and switch between multiple PHP versions
  • How to verify PHP is working and troubleshoot issues
  • How to configure integration with Apache or Nginx
  • How to install commonly used PHP modules
侍エンジニア塾

2. Prerequisites and Preparation

How to Check Your Ubuntu Version

First, check which version of Ubuntu you’re using. The installation steps and available PHP modules may vary slightly depending on your Ubuntu version.

You can check your Ubuntu version with this command:

lsb_release -a

Alternatively, you can use the following command:

cat /etc/os-release

This article is based on Ubuntu 22.04 LTS, but the basic procedure also applies to 20.04 and 23.10.

Keep Your System Packages Up to Date

Before installing PHP, it’s essential to update your system packages to the latest versions. This helps avoid dependency issues or inconsistencies. Update with the following commands:

sudo apt update
sudo apt upgrade -y

This refreshes the APT package index, making sure you’re installing the latest packages.

Install Required Utilities

When installing some PHP versions, you’ll need the software-properties-common package to add repositories and manage packages. If not already installed, do so with:

sudo apt install -y software-properties-common

This package is needed for commands like add-apt-repository, especially when using a PPA (Personal Package Archive) to install specific PHP versions.

Using Root Privileges or Sudo

Most steps in this article involve making system changes, so you’ll need to use sudo with your commands. If you’re not familiar with it, review the basics of the sudo command before proceeding.

3. How to Install PHP

There are two main ways to install PHP on Ubuntu: using the default repository, or specifying a version via a PPA (Personal Package Archive). We’ll walk through both methods.

Installing PHP from the Default Repository

The Ubuntu default repository provides stable versions of PHP. If you don’t need a specific version, simply run:

sudo apt install -y php

After installation, check that PHP is installed correctly:

php -v

Example:

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

On Ubuntu 22.04, PHP 8.1 is provided by default.

Installing a Specific Version Using PPA

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

Step 1: Add the PPA Repository

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

This repository is widely used in the Ubuntu community and offers stable builds for all major PHP versions.

Step 2: Install Your Desired PHP Version

For example, to install PHP 8.2:

sudo apt install -y php8.2

You can also install other versions like PHP 7.4 or 8.0 in the same way.

Step 3: Check the Installed Version

php -v

If the specific version was installed successfully, it will be displayed here.

4. Verifying PHP Installation

Once PHP is installed, check that it’s working. On Ubuntu, you can verify it via the command line (CLI) and also through your web server (Apache or Nginx). Here’s how:

Checking via Command Line (CLI)

Display the PHP version in the terminal to confirm that PHP is working:

php -v

If you see the PHP version and build information, PHP is working in the CLI.

Sample 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

Checking via Web Server (Apache Example)

If you’re using Apache, create a test page with the phpinfo() function to verify PHP is working with Apache.

1. Create the Test File

Create a PHP file in your Apache web directory (usually /var/www/html) with:

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

2. Check in Your Browser

Access the file in your browser. On your local machine, visit:

http://localhost/info.php

3. Review the Output

If you see detailed PHP information, PHP is working via Apache.

🔍 Tip: Since phpinfo() can display sensitive information, delete the info.php file after checking.

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

Checking with Nginx + PHP-FPM

If you use Nginx, PHP runs through php-fpm. Make sure Nginx is configured to handle .php files, then create info.php as above. If you see a 500 error or a download prompt, check your Nginx settings, especially fastcgi_pass and include fastcgi-php.conf;.

5. Installing Commonly Used PHP Modules

PHP’s core installation doesn’t include all features. Many are provided as modules (extensions) that must be installed as needed. Here, we introduce essential PHP modules for development and production.

What Are PHP Modules?

PHP modules (or extensions) add features like database connectivity, multibyte string processing, image manipulation, or XML handling.

Modules are available as APT packages and can be installed like this:

sudo apt install php-[module-name]

To specify a version, use something like php8.2-mbstring.

Key PHP Modules and Their Uses

php-mbstring (Multibyte String Support)

Required for handling multibyte characters like Japanese. Essential for Japanese sites or email processing.

sudo apt install php-mbstring

php-mysql (MySQL/MariaDB Connectivity)

Needed to connect to MySQL or MariaDB databases. Required for apps like WordPress that use a database.

sudo apt install php-mysql

php-gd (Image Processing)

Handles image creation, conversion, and resizing; used for generating screenshots or thumbnails.

sudo apt install php-gd

php-xml (XML Processing)

Required for handling XML-based data such as RSS feeds or SOAP. Used in CMSs and for API integration.

sudo apt install php-xml

php-curl (HTTP Communication)

Used for sending HTTP requests, like when integrating with external APIs. Widely used by modern frameworks.

sudo apt install php-curl

php-zip (ZIP File Handling)

Handles compressing and extracting ZIP files; useful for file upload features.

sudo apt install php-zip

Enabling Modules and Restarting Services

Some modules require explicit enabling after installation. Use phpenmod as follows:

sudo phpenmod [module-name]
sudo systemctl restart apache2

Changes take effect after restarting your web server.

6. Managing and Switching PHP Versions

Ubuntu lets you install and use multiple PHP versions on a single server. This is handy when hosting multiple apps or developing in various environments. Here’s how to switch versions on the CLI and with Apache.

Switching PHP Versions in the CLI

Command: update-alternatives

Use update-alternatives to easily switch the PHP version used in the CLI.

Step 1: List Installed PHP Versions

ls /usr/bin/php*

Step 2: Register PHP Versions with update-alternatives (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 Version to Use

sudo update-alternatives --config php

This shows a selection screen like:

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:

Type the number for your desired version and press Enter.

Step 4: Confirm the Version

php -v

Switching PHP Versions with Apache

With Apache, you can enable or disable PHP modules by version. Here’s how to select your preferred version:

1. List Available Modules

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

2. Disable the Current Module

sudo a2dismod php7.4

3. Enable the Desired Version

sudo a2enmod php8.2

4. Restart Apache

sudo systemctl restart apache2

This applies your changes to both the CLI and Apache.

7. Configuring Integration with Apache and Nginx

PHP becomes truly powerful when integrated with a web server. On Ubuntu, you’ll usually use either Apache or Nginx. Here’s how to connect PHP with both.

Configuring Apache (mod_php)

With Apache, the mod_php module allows PHP scripts to run directly. It’s easy to set up, making it a good choice for WordPress and other CMSs.

Step 1: Install Apache and mod_php

sudo apt install -y apache2 libapache2-mod-php

With libapache2-mod-php installed, Apache can process PHP files.

Step 2: Restart Apache

sudo systemctl restart apache2

Step 3: Test with a PHP File

Create a test.php file in /var/www/html and check in your browser:

<?php
phpinfo();
?>

Example URL:

http://localhost/test.php

Configuring Nginx (PHP-FPM)

Nginx is lightweight and fast, but can’t process PHP directly. You’ll use PHP-FPM (FastCGI Process Manager) for PHP support.

Step 1: Install Nginx and PHP-FPM

sudo apt install -y nginx php-fpm

Step 2: Edit the Nginx Config File

Edit /etc/nginx/sites-available/default (or your virtual host config):

sudo nano /etc/nginx/sites-available/default

Add or update this block:

location ~ .php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

Step 3: Restart Nginx

sudo systemctl restart nginx

Step 4: Test with a PHP File

Create /var/www/html/test.php and check in your browser, as with Apache.

Note: Firewall Settings (If Needed)

If using UFW (Uncomplicated Firewall), allow access with:

sudo ufw allow 'Apache Full'
# or
sudo ufw allow 'Nginx Full'

Apache is easy to set up, while Nginx offers high performance. Choose the best fit and ensure PHP integration is configured correctly.

8. Troubleshooting

Sometimes PHP may not work as expected, even after installation and server integration. This section covers common problems, their causes, and solutions.

PHP Not Working (Source Code Shown in Browser)

Cause

This occurs when Apache or Nginx outputs the PHP file as plain text instead of processing it. The PHP module or FastCGI settings may not be configured properly.

Solution

  • For Apache:
    Check that libapache2-mod-php is installed and enabled, then restart Apache.
  sudo apt install libapache2-mod-php
  sudo systemctl restart apache2
  • For Nginx:
    Check that php-fpm is installed and that the Nginx config has the correct fastcgi_pass and settings.
  sudo systemctl restart php8.2-fpm
  sudo systemctl restart nginx

Some PHP Features Not Working (Functions Undefined)

Cause

This is usually because the required PHP module is not installed or enabled.

Solution

  • Install the needed module(s), such as mbstring, xml, or curl:
  sudo apt install php-mbstring php-xml php-curl
  • After enabling a module, restart your web server.
  sudo systemctl restart apache2  # or nginx
  • Check enabled modules with:
  php -m

PHP Errors Not Displayed

Cause

By default, PHP error messages might be turned off.

Solution

Edit php.ini and change the error display settings:

sudo nano /etc/php/8.2/apache2/php.ini

Find and set the following:

display_errors = On
error_reporting = E_ALL

Then restart your web server:

sudo systemctl restart apache2

How to Check Error Logs

For Apache:

/var/log/apache2/error.log

For Nginx:

/var/log/nginx/error.log

For PHP-FPM (with Nginx):

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

Check these logs for troubleshooting:

sudo tail -f /var/log/apache2/error.log

When errors occur, remember: Check logs → Review configuration → Restart server. Stay calm and troubleshoot step by step.

9. Conclusion

This article explained—from basics to advanced steps—how to install PHP on Ubuntu. Here are the key points and next steps to explore.

Summary of Key Points

  • Check Ubuntu Version and Prepare
    Checking your OS version and updating packages is crucial for a smooth PHP installation.
  • Two Ways to Install PHP
    Install easily from the default repository, or use a PPA for specific versions.
  • Verify After Installing
    Use php -v and phpinfo() to check PHP in CLI and web contexts.
  • Extend Functionality with Modules
    Install commonly used modules like php-mbstring and php-mysql as needed.
  • Switch Between Multiple Versions
    Easily manage versions with update-alternatives or Apache module switching.
  • Proper Integration with Apache/Nginx
    Appropriate configuration with your chosen web server ensures stable operation.
  • Check Logs for Troubleshooting
    If PHP doesn’t display or work correctly, reviewing the error logs is the most effective first step.

Next Steps to Learn

After installing PHP on Ubuntu, you may want to dive deeper with these related topics:

  • Installing MySQL (MariaDB) and Connecting Databases
  • Installing and Setting Up WordPress
  • Using PHP Frameworks Like Laravel
  • Enabling HTTPS (Setting up SSL Certificates with Let’s Encrypt)
  • Managing Auto-Start and Restarts (Using systemd)

With these, you can build even more advanced web services and applications. Ubuntu and PHP together offer a robust, flexible open-source development environment. Use this article as your foundation to step up to new projects!

10. Frequently Asked Questions (FAQ)

This FAQ covers common stumbling blocks and questions that users often search for when installing or configuring PHP on Ubuntu. Answers are kept simple and practical, even for beginners.

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

A1.
The latest PHP version is not always in Ubuntu’s default repository. Add the trusted ondrej/php PPA, then install the version you want.

sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install php8.2

Q2. How can I switch PHP versions on the CLI?

A2.
If you have multiple versions installed, use update-alternatives to switch between them.

sudo update-alternatives --config php

Enter the number for your preferred version from the list displayed.

Q3. Apache shows my PHP file as plain text instead of executing it.

A3.
This means Apache is not processing PHP—it’s outputting it as plain text. Check that the libapache2-mod-php module is enabled and restart Apache:

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

Q4. Where is the PHP configuration file (php.ini) located?

A4.
There are separate files for CLI and web server use. The common locations are:

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

The “8.2” part changes depending on your PHP version.

Q5. How do I enable a PHP extension?

A5.
After installing, enable the module with phpenmod:

sudo phpenmod mbstring
sudo systemctl restart apache2

Restart your web server after enabling.

Q6. PHP is not working properly with Nginx. What should I check?

A6.
Nginx requires php-fpm to process PHP. Make sure your config includes the correct fastcgi_pass entry:

location ~ .php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

Adjust the .sock part according to your PHP version.

Q7. PHP errors are not shown on screen.

A7.
In php.ini, display_errors may be set to Off. For development, you can enable it like this:

display_errors = On
error_reporting = E_ALL

Restart your web server after making changes.

These FAQs will help you avoid common pitfalls when using PHP on Ubuntu. Keep this knowledge handy for smoother troubleshooting!

侍エンジニア塾