How to Install PHP on Ubuntu

  • Post category:Ubuntu

PHP (Hypertext Preprocessor) is a popular server-side scripting language widely used for web development. It powers many content management systems, frameworks, and applications. This guide will walk you through the process of installing PHP on Ubuntu, including optional modules that enhance functionality.

Step 1: Update the Package Repository

Before installing any software, it’s essential to update your package list.

Step 1.1: Open Terminal

Press Ctrl + Alt + T to open the terminal.

Step 1.2: Update Package List

Run the following command to update the package list:

sudo apt update

Step 2: Install PHP

Now, let’s install PHP on your system.

Step 2.1: Install PHP

To install PHP 8.1 (the default version in Ubuntu 22.04), run:

sudo apt install php

Step 2.2: Verify Installation

To ensure PHP was installed successfully, check its version:

php --version

Step 3: Install Additional PHP Modules (Optional)

Depending on your application needs, you may want to install additional PHP modules. Here are some common ones:

Step 3.1: Install MySQL Support

For MySQL support, run:

sudo apt install php-mysql

Step 3.2: Install PostgreSQL Support

To install PostgreSQL support, run:

sudo apt install php-pgsql

Step 3.3: Install Command Line Interface

If you want to use PHP from the command line, install the CLI module:

sudo apt install php-cli

Step 3.4: Install Multiple Modules

You can also install multiple modules in one command. For example:

sudo apt install php-{mysql,cli,gd,zip}

Step 4: Configure Apache (If Using Apache)

If you’re using Apache as your web server, you need to enable the PHP module.

Step 4.1: Install Apache and PHP Module

If you haven’t already installed Apache, do so now along with the PHP module:

sudo apt install apache2 libapache2-mod-php

Step 4.2: Restart Apache

Restart Apache to apply the changes:

sudo systemctl restart apache2

Step 5: Test Your PHP Installation

Let’s verify that PHP is working correctly.

Step 5.1: Create a Test PHP File

Create a new PHP file named info.php in the web server’s root directory (/var/www/html/):

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

Step 5.2: Access the Test File

Open a web browser and navigate to:

  • Local Machine: http://localhost/info.php
  • Remote Server: http://your_server_ip/info.php

You should see the PHP information page displaying various configuration settings.

Conclusion

Congratulations! You have successfully installed PHP on your Ubuntu system, along with any necessary modules for your applications. For more advanced configurations, refer to the official PHP documentation.

Explore more guides and tutorials on web development and server management at CodeAllow.