Sign In
Sign In

How to Install PHP and PHP-FPM on Ubuntu 24.04

How to Install PHP and PHP-FPM on Ubuntu 24.04
Adnene Mabrouk
Technical writer
PHP Ubuntu
09.12.2024
Reading time: 6 min

In this guide, we will describe installing PHP and PHP-FPM on Ubuntu 24.04. PHP, which stands for Hypertext Preprocessor, is a language that is widely used and open-sourced, mainly for web development. PHP is the only PHP FastCGI implementation, that is extremely useful for high-traffic websites. At the end of this guide, you should be ready to go with PHP running on your server.

Prerequisites

Before we start, please confirm you have the following:

  • Ubuntu 24.04 LTS installed on the server
  • A user account with the sudo access
  • An essential command-line operation understanding
  • A reliable internet connection for downloading software packages

To ensure that your system is up to date, run the following commands:

sudo apt update
sudo apt upgrade

Install Apache

Launch the Apache web server using the following command:

sudo apt install apache2

Install PHP

Let's begin with installing the PHP package in Ubuntu 24.04 server.

First, open a terminal on your Ubuntu system.

PHP and common modules are included in the installation action:

sudo apt install php

That command installs the core PHP package, the command-line interface, and common libraries.

Make sure the installation works:

php -v

Image1

Install PHP Extensions

PHP extensions are the way to go to extending PHP installation with certain functions. Start by installing extensions:

sudo apt install php-curl php-mbstring php-xml

Short description:

  • php-mysql: Allows MySQL database connection

  • php-gd: Adds ability to manipulate images

  • php-curl: Makes possible to communicate with servers

  • php-mbstring: Provides multibyte string support

  • php-xml: Enables XML support

  • php-zip: Enables ZIP support

Additional extensions can be installed as you see fit for your projects. You can search them using:

apt-cache search php-

Install and Configure PHP-FPM

PHP-FPM is essential when dealing with high-traffic websites. To install and configure it:

  1. Install the package:

sudo apt install php-fpm
  1. Launch PHP-FPM service. Depending on the installation, version number may differ.

sudo systemctl start php8.3-fpm
  1. Tell PHP-FPM to go on boot:

sudo systemctl enable php8.3-fpm
  1. Verfy PHP-FPM is working:

systemctl status php8.3-fpm

This will output a response that says "Active (Running)" if everything is working as expected.

Test PHP and PHP-FPM

To ensure that PHP and PHP-FPM are both running with no problems, create a test file then serve it via the website's server. Let's say it uses Apache in this example:

  1. Generate PHP Info File. To show PHP settings using the phpinfo() function, do the following:

mkdir -p /var/www/html
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
  1. Set Up Apache for PHP-FPM. Ensure Apache is made compatible for PHP-FPM, by first finding Apache configuration file (usually /etc/apache2/sites-available/000-default.conf) then inserting:

<FilesMatch \.php$>
  SetHandler "proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://localhost/"
</FilesMatch>

Remember we must alter specific PHP version and socket path to suit individual settings of the server.

  1. Activate PHP and PHP-FPM. Enable PHP and PHP-FPM following these instructions:

sudo apt install libapache2-mod-php
sudo a2enmod proxy_fcgi setenvif
  1. Reboot Apache. Apply changes by restarting Apache server:

sudo systemctl restart apache2
  1. Access PHP Info Page. First open your web browser and go to:

http://your_server_ip/info.php

Replace [server_ip] with the server IP address or domain. You can see details of your PHP installation.

Image2

Install Multiple PHP Versions

For particular projects you might need to run different applications, each one may require different functionalities. This is the way to manage and manipulate multiple PHP versions on Ubuntu 24.04.

First, add PHP repository:

sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php && sudo apt update

Install PHP versions you need:

sudo apt install php8.1 php8.1-fpm

Deselect one PHP version and elect the other:

sudo update-alternatives --set php /usr/bin/php8.1

If you are using multiple PHP versions, ensure that your web server is pointing to the appropriate PHP-FPM socket.

Securing PHP and PHP-FPM: Best Practices

As a web developer, you know the importance of incorporating both PHP and PHP-FPM into web applications that are safe and robust. In this section, we will introduce a number of security steps that you should adapt using PHP and PHP-FPM.

1. Keep PHP and PHP-FPM Updated

PHP and PHP-FPM should be up to date. Doing regular updates will eliminate known security breaches and provide overall security improvements. You need to check for updates as often as possible then update the system as soon as the updates are available.

2. Configure PHP Securely

To configure PHP securely, start by disabling unnecessary and potentially dangerous functions, such as exec, shell_exec, and eval, in the PHP configuration file (php.ini). Use open_basedir directive to restrict PHP’s access to specific directories, preventing unauthorized access to sensitive files. Set display_errors to Off in production to avoid exposing error messages that could provide insights to attackers. Limit file upload sizes and execution times to reduce the risk of resource exhaustion attacks. Besides, ensure that PHP runs under a dedicated, restricted user account with minimal permissions to prevent privilege escalation. Regularly update PHP to the latest stable version to patch vulnerabilities and improve security.

3. Use Safe Error Reporting

To ensure an error-free application, it is quite handy locating and correcting code bugs in a development environment. In production environment, you have the possibility to hide the PHP errors by setting the display_error directive to be off, and you should also set the log_errors directive to be On, thus this will help you prevent PHP from showing errors to the users whereas your server will log it in a safe location without problems to users.

4. Implement Input Validation

Being aware of the input validations is quite crucial during the programming of your software. Make sure that all deficiencies are tested and only SQL statements containing their SQL equivalent that can produce outwardly neutral queries via prepared statements is considered safe.

5. Secure PHP-FPM Configuration

PHP-FPM is required to run using a non-usual user account with minium rights. Furthermore, access to the PHP-FPM socket or port should be very limited to the web application.

6. Enable Open_basedir

You need to bind open_basedir directive in order to restrict access files within the given directory. In this case, if you attempt to visit a forbidden directory and the request is accidentally transmitted to the server, PHP will prevent you from doing so.

7. Use HTTPS

We need to secure web calls by making apps HTTPS-only, which is the only prominent way to block all the known hacking tricks.

Conclusion

With this guide, you've successfully set up PHP and PHP-FPM on Ubuntu 24.04. Your server is now configured for dynamic web applications. To maintain security and performance, remember to keep the system and packages regularly updated.

PHP Ubuntu
09.12.2024
Reading time: 6 min

Similar

Ubuntu

How to Install and Use Composer on Ubuntu

Composer is a cross-platform tool for managing dependencies in projects written in PHP. With Composer, you can manage numerous libraries and frameworks, known as "packages." Installing the required packages allows you to extend the standard PHP functionality, speeding up and simplifying development. All installed packages become project dependencies. Thus, Composer can be considered a full-fledged dependency manager, similar to those used in many programming languages. Additionally, Composer has a comprehensive package repository called Packagist, where you can search for, download, and install the required packages. This guide provides detailed instructions on installing Composer on an Ubuntu server and using it for PHP projects. Prerequisites In this tutorial, we use: A VPS server running Ubuntu 22.04 PHP interpreter version 8.1.2 Composer dependency manager version 2.8.2 Installing Composer First, update the list of existing APT repositories: sudo apt update Next, install the packages required to download and use Composer: sudo apt install curl php-cli unzip -y These packages include: curl: A tool for making HTTP requests. php-cli: An interpreter to run PHP scripts. unzip: A utility to extract ZIP archives. The -y flag answers "yes" to all installation prompts. Composer installation is automated using a PHP script provided by its developers. Download the installation script from the official Composer website using an HTTP request: curl -sS https://getcomposer.org/installer -o composerInstall.php The -sS flag runs curl in silent mode, suppressing all output except for errors. The -o flag specifies the filename and the directory where the file will be placed. To ensure the file has been downloaded, check the contents of the current directory: ls You should see the following output in the terminal, including the installation script: composerInstall.php  resize.log  snap This guide covers the global installation of Composer, meaning it can be run from any directory without specifying the absolute path. To perform a global installation, execute the downloaded PHP script with additional parameters: php composerInstall.php --install-dir=/usr/local/bin --filename=composer The --install-dir flag specifies the directory where Composer will be installed. The --filename flag defines the name of the binary file accessible from the terminal. In this case, Composer is installed in the system's binary directory: /usr/local/bin. After running the script, you'll see the following output in the terminal: All settings correct for using Composer Downloading... Composer (version 2.8.2) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer Since the installation script is no longer needed, you can delete it: rm composerInstall.php To launch Composer for the first time, run: composer You may see the following message in the terminal: Do not run Composer as root/super user! See https://getcomposer.org/root for details Continue as root/super user [yes]? Composer warns against running it as the root user due to potential risks but allows you to proceed. For this guide, we will continue using Composer as-is by confirming with yes. Afterward, you will see a welcome message along with a list of available options and commands with brief descriptions. Composer is now fully installed. Configuring Composer The main file used to manage dependencies is composer.json, which describes the packages required for the proper functioning of a project. Composer follows the Infrastructure as Code (IaC) approach, describing the local project infrastructure through a configuration file rather than manual settings adjustments in a graphical interface. However, Composer allows configuration management not only by manually editing the file in a text editor but also through console commands, providing a more interactive way to handle configurations. Basic Commands Using Composer involves several fundamental commands that interact with the composer.json configuration file: init: Initializes a project. require: Adds a package. install: Installs dependencies. update: Updates packages. Although Composer offers many more commands, these are the most frequently used. Creating a Directory Create a separate directory for the PHP project: mkdir phptest Then navigate to the directory: cd phptest This directory will store both the project’s source code and the required dependency files. Searching for a Library Suppose we are working on a small project that performs various string transformations. As a dependency, we need a specific library that provides functions for manipulating string content. In this guide, we will implement a common programming function called slugify, which converts a sequence of words into a single long word containing only lowercase ASCII characters and hyphens. The slugify function is often used to transform arbitrary headings into URL-friendly formats without spaces. Rather than writing this function ourselves, we will use Composer to find a suitable library in the official package registry, add it as a dependency, and let Composer handle its download, installation, and integration into the project. To find the necessary library, follow these steps: Open the Composer's official package registry in a browser. Enter "slugify" in the search bar. Look for the most suitable package based on its parameters and description. The search results display key metrics for each available package: The number of installations via Composer (top right) The number of GitHub stars (bottom right) In general, popular packages tend to be more stable since they are used by a larger number of developers. Selecting a Package In this guide, we will use the package cocur/slugify. The package name, similar to a GitHub repository, contains the author (provider) and the library name separated by a forward slash (/). We can navigate to the package's page by clicking its name to see more details about the library’s implementation, such as dependency lists, descriptions with code examples, test coverage badges, license type, and more. Additionally, pay attention to the available package versions, as you need to specify the version during dependency installation. By following this process, you can search for and select suitable packages for a PHP project, which can later be used as dependencies to provide specific functions. Installing a Dependency To install the required package, use the require command. This either records the dependency in the composer.json configuration file or creates it if it does not exist: composer require cocur/slugify:4.6 In this guide, we are using cocur/slugify version 4.6.0. After running the command, you might encounter an error indicating missing system libraries: ./composer.json has been created Running composer update cocur/slugify Loading composer repositories with package information Updating dependencies Your requirements could not be resolved to an installable set of packages. Problem 1 - Root composer.json requires cocur/slugify 4.1 -> satisfiable by cocur/slugify[v4.1.0]. - cocur/slugify v4.1.0 requires ext-mbstring * -> it is missing from your system. Install or enable PHP's mbstring extension. This console output informs us that the ext-mbstring system library is missing, which is necessary for cocur/slugify to work correctly. You can manually search for the library using the APT package manager: sudo apt search mbstring The search results will show: Sorting... Done Full Text Search... Done php-mbstring/jammy 2:8.1+92ubuntu1 all MBSTRING module for PHP [default] php-patchwork-utf8/jammy 1.3.1-1 all UTF-8 strings handling for PHP php-symfony-polyfill-mbstring/jammy 1.24.0-1ubuntu2 all Symfony polyfill for the Mbstring extension php-symfony-polyfill-util/jammy 1.24.0-1ubuntu2 all Symfony utilities for portability of PHP codes php8.1-mbstring/jammy-updates,jammy-security 8.1.2-1ubuntu2.19 amd64 MBSTRING module for PHP The first result is the library we need. Install it with: sudo apt install php-mbstring -y Once the missing library is installed, rerun the command to install the package: composer require cocur/slugify:4.6 This time, the console output should confirm a successful installation: ./composer.json has been created Running composer update cocur/slugify Loading composer repositories with package information Updating dependencies Lock file operations: 1 install, 0 updates, 0 removals - Locking cocur/slugify (v4.6.0) Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Downloading cocur/slugify (v4.6.0) - Installing cocur/slugify (v4.6.0): Extracting archive Generating autoload files No security vulnerability advisories found. Check the directory contents with: ls You will see new files generated by Composer: composer.json  composer.lock  vendor Each file and directory serves a specific purpose: composer.json — Contains information about the required dependencies composer.lock — Records details about installed dependencies vendor — Stores the project’s installed dependencies If you use a version control system like Git, exclude the vendor directory from the repository. Take a look inside composer.json: cat composer.json It should look like this: { "require": { "cocur/slugify": "4.6" } } You’ll notice the require block specifying the package cocur/slugify version 4.6. You can find more detailed information about possible version values in the official Composer documentation. Using Composer Including Dependencies Once you have installed a dependency, you can include it in the project code using the automatically generated autoload.php script, located in the vendor directory. When this script is included in the PHP application, the functions and classes of the installed dependencies become available for use. Let's create the main file of our application: sudo nano main.php Then, fill it with the following content: <?php require __DIR__ . '/vendor/autoload.php'; use Cocur\Slugify\Slugify; $slugify = new Slugify(); // PHP_EOL is needed for line breaks in the console echo '[english]: ' . $slugify->slugify('How to deal with composer') . PHP_EOL; ?> Now, you can run the script: php main.php The output in the console terminal should look like this: [english]: how-to-use-composer Updating Dependencies Composer allows you to check for new versions of libraries based on version ranges defined in the composer.json configuration file: composer update Alternatively, you can update a specific package by specifying its name: composer update cocur/slugify Installing Dependencies If your PHP project contains a composer.json file, but the specified dependencies are not yet installed, you need to install them. Let’s first remove all existing packages and related information: rm -R vendor composer.lock The -R flag is necessary for recursive deletion of files and directories. After that, try running the script: php main.php You will see the expected error message in the console because the dependencies are missing: PHP Warning: require(/root/phptest/vendor/autoload.php): Failed to open stream: No such file or directory in /root/phptest/main.php on line 2 PHP Fatal error: Uncaught Error: Failed opening required '/root/phptest/vendor/autoload.php' (include_path='.:/usr/share/php') in /root/phptest/main.php:2 Stack trace: #0 {main} thrown in /root/phptest/main.php on line 2 Now, let's reinstall the dependencies based on the data from the configuration file: composer install After that, run the script again: php main.php The console should display the expected result without any errors: [english]: how-to-install-and-use-composer Conclusion You can install Composer on Ubuntu 22.04 automatically using an installation script from the official Composer website. Although Composer has many commands to manage the composer.json configuration file, in practice, only a few basic ones are commonly used: composer init composer require composer install composer update You can find comprehensive information on how to use Composer in the official documentation.
14 February 2025 · 10 min to read
PHP

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

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: Connect to the server via SSH. Update the package list: sudo apt update Install the required dependencies: sudo apt install build-essential libssl-dev 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 Extract the downloaded file, replacing <version> with the downloaded version: tar xzf php-<version>.tar.gz Navigate to the directory with the installed PHP: cd php-<version> Configure the installation script: ./configure Build PHP: make 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 GroupZend Engine v4.3.13, Copyright (c) Zend Technologies    with Zend OPcache v8.3.13, Copyright (c), by Zend Technologies Check PHP Version with phpinfo() Create a file named phpinfo.php with the following content: <?phpphpinfo( );?> Save the file in the root directory of your website (where the index.html or index.php file is located). 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. Check if multiple PHP versions are installed. To see the list of installed PHP packages, run the command: dpkg --list | grep php Install the php-switch package, which allows change PHP versions easily: sudo apt-get install -y php-switch Switch to the desired PHP version using the php-switch command. For example, to switch to PHP 7.4, run: php-switch 8.2 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.
20 November 2024 · 5 min to read
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