Sign In
Sign In

Installing and Switching PHP Versions on Ubuntu: A Step-by-Step Guide

Installing and Switching PHP Versions on Ubuntu: A Step-by-Step Guide
Hostman Team
Technical writer
PHP Ubuntu
20.11.2024
Reading time: 5 min

PHP is a scripting programming language commonly used for developing web applications. It allows developers to create dynamic websites that adapt their pages for specific users. These websites are not stored on the server in a ready-made form but are created on the server after a user request. This means that PHP is a server-side language, meaning scripts written in PHP run on the server, not the user's computer.

There are many different versions of PHP. The language becomes more powerful and flexible with each new version, offering developers more opportunities to create modern web applications. However, not all websites upgrade or are ready to upgrade to the latest PHP version and remain on older versions.

Therefore, switching between versions is an essential task for many web developers. Some developers want to take advantage of new features introduced in newer versions, while others need to fix bugs and improve the security of existing applications. In this article, we will go over how to install PHP on Ubuntu and how to manage different PHP versions.

How to Install PHP on the Server

To install PHP on Ubuntu Server, follow these steps:

  1. Connect to the server via SSH.

  2. Update the package list:

sudo apt update
  1. Install the required dependencies:
sudo apt install build-essential libssl-dev
  1. Download the installation script from the official website, replacing <version> with the desired version:
curl -L -O https://www.php.net/distributions/php-<version>.tar.gz
  1. Extract the downloaded file, replacing <version> with the downloaded version:
tar xzf php-<version>.tar.gz
  1. Navigate to the directory with the installed PHP:
cd php-<version>
  1. Configure the installation script:
./configure
  1. Build PHP:
make
  1. Install PHP:
sudo make install

After completing these steps, PHP will be installed on your server. The next step is to install a web server to work with PHP. The configuration may involve specifying the PHP module in the web server configuration file and setting up how .php files are handled.

Finally, restart the web server. For example, to restart Apache, you can run the following command:

sudo service apache2 restart

How to Check PHP Version

There are several ways to find out which version of PHP a website is running:

  • Use the terminal.
  • Create a script with phpinfo() in the website's root directory.

Check PHP Version via Terminal

Run the command in the terminal:

php -v

You will get output similar to:

PHP 8.3.13 (cli) (built: Oct 30 2024 11:27:41) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.3.13, Copyright (c) Zend Technologies
   with Zend OPcache v8.3.13, Copyright (c), by Zend Technologies

Check PHP Version with phpinfo()

  1. Create a file named phpinfo.php with the following content:

<?php
phpinfo( );
?>
  1. Save the file in the root directory of your website (where the index.html or index.php file is located).

  2. Open this file in your browser by using the following URL:

http://your_website_address/phpinfo.php

You will see a page with detailed information about the PHP configuration.

After finding out the PHP version, be sure to delete the phpinfo.php file as it contains important server configuration information that attackers could exploit.

How to Manage PHP Versions

To switch between installed PHP versions on Ubuntu, follow these steps.

  1. Check if multiple PHP versions are installed. To see the list of installed PHP packages, run the command:
dpkg --list | grep php
  1. Install the php-switch package, which allows change PHP versions easily:
sudo apt-get install -y php-switch
  1. Switch to the desired PHP version using the php-switch command. For example, to switch to PHP 7.4, run:
php-switch 8.2
  1. Verify which PHP version is currently active by running:
php -v

Some scripts and extensions may only work with certain PHP versions. Before switching, make sure that all the scripts and extensions you are using support the new version. Otherwise, the website may become inaccessible or malfunction.

Troubleshooting

If PHP scripts are not being processed on your server, the first thing to check is the web server's functionality. Open a browser and go to the website where PHP scripts are not working. If the page opens but the PHP script output is not displayed, the problem may lie with PHP.

Here are some steps you can take to troubleshoot the issue.

Check PHP Service Status

Run the following command, using your PHP version (e.g., PHP 8.3):

sudo service php8.3-fpm status

If the service is running, the output should indicate active (running). If the service is not running, start it with this command:

sudo service php8.3-fpm start

Check PHP Log Files

To view PHP log files, use the following command:

tail /var/log/php7\8.3-fpm.log

This command will display the last few lines of the PHP log file, which may help identify the issue.

Check PHP Configuration

Open the php.ini file in a text editor and ensure the display_errors option is set to On. This will allow PHP errors to be displayed on your website pages.

Check for Script Errors

Open the PHP scripts in a text editor and look for syntax errors or other issues that could prevent the scripts from working properly.

Check for Web Server Restrictions

Check the web server configuration for any restrictions that might affect the execution of PHP scripts. For example, there may be restrictions in the .htaccess file that prevent certain directories from running scripts.

Test the Script on Another Server

If the script works on another server, the issue may be related to the configuration of the current server.

PHP Ubuntu
20.11.2024
Reading time: 5 min

Similar

MySQL

Photo Database with HTML, PHP, and MySQL

Storing images in a database with other information is convenient when your application strongly relies on the database. For example, you'll need to synchronize images with other data if you are developing a program for a checkpoint system; in this case, along with personal data, you need to store a photo to identify the person. There is a special MySQL data type for storing such content, BLOB. It accommodates large binary data: images, PDFs, or other multimedia files.  An alternative to using the BLOB type is storing images inside the file system. But in this case, we make the application less portable and secure; there are at least two closely related modules: file system and database. Besides, when creating backups, you won't need to take snapshots of system directories; it will be enough to save MySQL dumps. In this article, we will work on the photo database using a server with the LAMP stack installed (Linux, Apache2, MySQL, and PHP). You will need a user with sudo privileges to work with the server.  As an example, in this article, we'll be working on the university's checkpoint system app. Creating a database First, let's create a database for our new project. You can do this through the console or any DBMS interface, such as phpMiniAdmin. We will use the first option.  Connect to the server via SSH and log in to the MySQL server with superuser privileges: sudo mysql -u root -p Then, run the command to create the database. Let's call it access_control: mysql> CREATE DATABASE access_control; If you see an output like: Query OK, 1 row affected (0.01 sec), the database has been successfully created. Now we can start working with tables.  But before that, for security purposes, we need to create a separate user who will work only with this database. For convenience, let's name it the same as the database: mysql> CREATE USER 'access_control'@'localhost' IDENTIFIED BY 'Pas$w0rd!'; where passw0rd is your strong password.  Now let's grant it permissions for all operations on the access_control database: mysql> GRANT ALL PRIVILEGES ON access_control.* TO 'access_control'@'localhost'; After that, you need to clear the permissions table for MySQL to apply the changes: mysql> FLUSH PRIVILEGES; Now, we can start creating tables. We will need the students table, where we will store students' information, photos, and access rights.  Let's log into MySQL with the newly created access_control user:  mysql -u access_control -p Switch to our database: mysql> USE 'access_control'; And create the students table: CREATE TABLE `students` (    id INT INT PRIMARY KEY COMMENT "Student ID",    name VARCHAR(200) NOT NULL COMMENT "Student's full name",    access_rights ENUM ('full', 'extended', 'basic', 'denied') DEFAULT 'basic' COMMENT "Access Rights",    userpic BLOB COMMENT 'Student Photo',    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT "Enrollment Date") ENGINE = InnoDB; Here: id is the table's primary key, numeric identifier of students. When adding new records, MySQL will independently generate identifiers in ascending order because we used the AUTO_INCREMENT keyword. name is the student's full name. We use VARCHAR data type with a limit of 200, because we won't need more than 200 characters for the name. access_rights is access rights for the student. The ENUM type assumes that one value from the list will be selected. userpic is a student's photo. The BLOB data type will store the data in binary format. created_at is the date of record creation. When we add a new record, MySQL will automatically add the current timestamp to this column. We have chosen InnoDB to store the data, which will allow us to use a wide range of features, such as MySQL transactions. - Creating PHP scripts to fill in the database The students table is ready, so now we can load data into it. Let's write a PHP script to register students in the system and add data to students. First, let's create a configuration file config.php with database connection parameters. <?php$params = [     'user' => 'control_access',      'name' => 'control_access',      'host' => 'localhost',      'pass => 'Pas$w0rd!'];$pdo = new PDO(     'mysql:host=' . $params['host'] . '; dbname=' . $params['name'],     $params['user'],      $params['pass']); To work with the database, we use the PDO driver. It passes connection parameters (database name, user name, password and the server's address where the database is located).  Now, let's create a script to fill our table with test data. <?php// Connecting the configuration file require_once dirname(__FILE__) . '/config.php';// Filling the array with data$students = [     [        'name' => 'John Smith,        'access_rights' => 'basic',        'userpic' => file_get_contents(dirname(__FILE) . '/userpic/1.png')    ],    [        'name' => 'Juan Hernandez',        'access_rights' => 'full',        'userpic' => file_get_contents(dirname(__FILE) . '/userpic/2.png')    ],    [        'name' => 'Richard Miles',        'access_rights' => 'extended',        'userpic' => file_get_contents(dirname(__FILE) . '/userpic/3.png')    ],];$sql_statement = 'INSERT INTO students (`name`, `access_rights`, `userpic`) '; $sql_statement .= 'VALUES (:name, :access_rights, :userpic);'foreach($students as $student){    $query = $pdo->prepare($sql_statement);    $query->execute($student);}echo "done"; With this script, we connect to the database and then insert the necessary data. This script clearly shows how to add a picture to an SQL database; you just need to put its content in the appropriate field. To get the file's contents, we used the built-in php function file_get_contents. Then, we insert each array element into the database in a loop using the INSERT expression. Displaying information We have placed student information into the database; now, we need to display the data. We'll display everything in the table on a separate view.php page for convenience. <?php// Connect the config file require_once dirname(__FILE__) . '/config.php';// Query all records from the students table $query= $pdo->prepare('    SELECT        *    FROM        students');$query->execute();?><!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>MySQL BLOB test</title></head><body>    <table>        <thead>            <tr>                <td>Name</td>                <td>Access Rights</td>                <td>Photo</td>            </tr>        </thead>        <tbody>         <?php        while($row - $query->fetch(PDO::FETCH_ASSOC))        {            echo '<tr>';                echo '<td>' . $row['name'] . '</td>";                echo '<td>' . $row['access_rights'] . '</td>';                 echo '<td>';                    echo '<image src="data:image/png;base64,' . base64_encode($row['userpic']) . '"';                echo '</td>';            echo '</tr>';        }        </tbody>    </table></body></html> We again use the connection to PDO inside the config.php file and then request a sample of all students using the SELECT * FROM students expression.  We display all the obtained data in an HTML table. To output the data stored in the BLOB object to the browser, we encoded the data into base64 format using the php built-in function and used the following syntax when specifying the image source in the img tag: data:{type};base64, {data} where {type} is the data type, in our case image/png, and {data} is the base64 data.  Conclusion In this article, using a student checkout system as an example, we have learned how to store images in a database using the BLOB data type.  In addition, we learned how to insert media files into BLOB fields in managed MySQL and how to output them to the browser.
12 December 2023 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support