How to Install PHP on Debian: Complete Step-by-Step Guide

Published in

on

PHP (Hypertext Preprocessor) remains one of the most popular server-side scripting languages powering over 77% of websites worldwide, including platforms like WordPress, Drupal, and Laravel applications.

If you’re running latest Debian Linux and earlier versions like 12 (Bookworm), Debian 11 (Bullseye), or Debian 10 (Buster), installing PHP correctly is crucial for web development, hosting dynamic websites, and building robust web applications.

This comprehensive guide walks you through multiple methods to install PHP on Debian, configure it with Apache or Nginx web servers, install essential PHP extensions, and optimize your installation for production environments.

PHP on Debian

Whether you’re a beginner learning web development or an experienced system administrator deploying enterprise applications, this tutorial covers everything you need to know about PHP installation on Debian Linux.

Why Install PHP on Debian?

Before diving into installation steps, let’s understand why PHP on Debian makes an excellent combination for web hosting and development:

Stability and Reliability: Debian is renowned for its rock-solid stability, making it perfect for production servers running PHP applications. Debian’s extensive testing cycles ensure PHP packages work flawlessly with other system components.

Long-Term Support: Debian releases receive approximately five years of security updates and support, meaning your PHP installation remains secure without constant major version upgrades. This stability is invaluable for mission-critical web applications.

Extensive Package Repository: Debian provides over 59,000 packages, including PHP and hundreds of PHP extensions through its official repositories. You can easily install everything from PHP-MySQL connectors to image processing libraries with simple APT commands.

Enterprise-Grade Security: Debian’s security team actively monitors vulnerabilities and releases timely security patches. Combined with PHP’s regular security updates, your web applications remain protected against emerging threats.

Resource Efficiency: Debian’s minimal resource footprint means more system resources are available for PHP processing, resulting in better website performance and the ability to handle more concurrent requests.

Prerequisites Before Installing PHP on Debian.

Before proceeding with PHP installation, ensure you meet these requirements:

  • Debian System Access: You need a Debian 12, 11, or 10 system with root or sudo privileges
  • Updated System: Run system updates to ensure all packages are current
  • Internet Connection: Required for downloading PHP packages and dependencies
  • Basic Command Line Knowledge: Familiarity with Linux terminal and basic commands
  • Web Server (Optional): Apache or Nginx if you plan to serve PHP web pages

Let’s verify your Debian version before proceeding:

lsb_release -a

This command displays your Debian version, ensuring you follow the correct installation steps for your specific release.

Understanding PHP Versions Available on Debian.

Different Debian releases ship with different default PHP versions:

  • Debian 12 (Bookworm): PHP 8.2 (default in repositories).
  • Debian 11 (Bullseye): PHP 7.4 (default in repositories).
  • Debian 10 (Buster): PHP 7.3 (default in repositories).

However, modern web applications often require newer PHP versions like PHP 8.3 or PHP 8.4, or legacy applications may need older versions like PHP 7.4. This guide covers installing multiple PHP versions using the Ondřej Surý repository, a trusted third-party repository maintained by a Debian developer that provides up-to-date PHP packages for all supported versions.

Method 1: Install PHP from Default Debian Repositories (Quickest Method).

The simplest way to install PHP on Debian is using the default repositories. This method is perfect for users who don’t need bleeding-edge PHP versions and prefer the tested stability of Debian’s official packages.

Step 1: Update System Packages.

Always start by updating your package lists and upgrading existing packages to ensure system stability:

sudo apt update
sudo apt upgrade -y

The apt update command refreshes package information from repositories, while apt upgrade installs available updates for your currently installed packages. This ensures compatibility and reduces potential conflicts during PHP installation.

Step 2: Install PHP from Default Repositories.

Install PHP using APT package manager:

sudo apt install php -y

This command installs the default PHP version for your Debian release along with essential components like PHP CLI (Command Line Interface) for running PHP scripts from terminal.

Step 3: Verify PHP Installation.

Confirm PHP installed correctly and check the installed version:

php -v

You should see output similar to:

PHP 8.2.7 (cli) (built: Jun 9 2023 19:37:27) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.7, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.7, Copyright (c), by Zend Technologies

The output confirms PHP is installed and displays the version number, build date, and enabled extensions like Zend OPcache for performance optimization.

Step 4: Check PHP Configuration.

View PHP configuration settings:

php -i | grep php.ini

This displays the path to PHP’s configuration file (php.ini), typically located at /etc/php/8.2/cli/php.ini for PHP 8.2 on Debian 12. You’ll need this location later for customizing PHP settings.

Method 2: Install Specific PHP Versions Using Ondřej Surý Repository (Recommended).

For installing PHP 8.3, PHP 8.4, or any specific PHP version not available in default Debian repositories, use the reputable Ondřej Surý PHP repository. This repository is widely trusted by professionals and provides multiple PHP versions simultaneously.

Step 1: Install Required Dependencies.

First, install necessary packages for repository management and HTTPS support:

sudo apt update
sudo apt install lsb-release apt-transport-https ca-certificates software-properties-common wget curl gnupg2 -y

These packages enable:

  • lsb-release: Identifies your Debian version automatically
  • apt-transport-https: Allows APT to retrieve packages via HTTPS
  • ca-certificates: Validates SSL certificates for secure downloads
  • wget and curl: Download files from the internet
  • gnupg2: Verifies package signatures for security

Step 2: Add Ondřej Surý PHP Repository GPG Key.

Download and add the repository’s GPG key to verify package authenticity:

sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg

GPG keys ensure packages haven’t been tampered with during download, protecting your system from malicious software.

Step 3: Add Surý Repository to APT Sources.

Add the repository information to your APT sources list:

echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php.list

This command:

  1. Creates the repository URL using your Debian codename automatically
  2. Saves it to /etc/apt/sources.list.d/php.list
  3. Enables APT to discover PHP packages from this repository

Step 4: Update Package Lists.

Refresh APT’s package cache to include packages from the new repository:

sudo apt update

You should see messages indicating APT is downloading package information from packages.sury.org, confirming the repository was added successfully.

Step 5: Check Available PHP Versions.

View all PHP versions available for installation:

sudo apt-cache policy php

Output shows available versions like:

php:
  Installed: (none)
  Candidate: 2:8.3+94+0~20240205.51+debian12~1.gbp6faa2e
  Version table:
     2:8.3+94+0~20240205.51+debian12~1.gbp6faa2e 500
        500 https://packages.sury.org/php bookworm/main amd64 Packages
     2:8.2+93 500
        500 https://deb.debian.org/debian bookworm/main amd64 Packages

This confirms PHP 8.3 is available from Surý repository while PHP 8.2 comes from official Debian repositories.

Step 6: Install Your Desired PHP Version.

Install a specific PHP version (replace 8.3 with your desired version):

# Install PHP 8.3
sudo apt install php8.3 -y

# Or install PHP 8.2
sudo apt install php8.2 -y

# Or install PHP 7.4 for legacy applications
sudo apt install php7.4 -y

The installation includes PHP CLI and core components. For web server integration, you’ll need additional packages covered in later sections.

Step 7: Verify Installation.

Confirm the installed version:

php -v

If you have multiple PHP versions installed, this shows the currently active version in your PATH.

Installing Multiple PHP Versions on Debian (Advanced).

Modern web hosting often requires running multiple PHP versions simultaneously for different applications. The Ondřej Surý repository makes this straightforward.

Install Multiple Versions Side-by-Side.

Install several PHP versions without conflicts:

sudo apt install php7.4 php8.0 php8.1 php8.2 php8.3 -y

Each version installs to separate directories under /etc/php/ and can run independently through different PHP-FPM pools or Apache modules.

Switch Between PHP CLI Versions.

Use update-alternatives to switch the default CLI PHP version:

# List available PHP versions
sudo update-alternatives --display php

# Set PHP 8.3 as default CLI version
sudo update-alternatives --set php /usr/bin/php8.3

# Or interactively choose version
sudo update-alternatives --config php

The interactive mode presents a menu where you select your preferred PHP version by number. This affects php command behavior but doesn’t change web server PHP versions, which require separate configuration.

Verify Active PHP Version.

Check which version is currently active:

php -v
which php

The which php command shows the path to the active PHP binary, helping verify your version switch was successful.

Essential PHP Extensions Installation.

PHP extensions add functionality for database connectivity, image manipulation, caching, and more. Most web applications require several extensions beyond the base PHP installation.

Understanding PHP Extension Naming.

PHP extensions follow the naming pattern php{VERSION}-{EXTENSION}. For example:

  • php8.3-mysql: MySQL database support for PHP 8.3
  • php8.2-curl: cURL support for PHP 8.2
  • php7.4-gd: GD image library for PHP 7.4

Install Common PHP Extensions.

Install the most frequently used PHP extensions (replace 8.3 with your PHP version):

sudo apt install php8.3-cli php8.3-fpm php8.3-mysql php8.3-mysqli php8.3-pdo php8.3-curl php8.3-xml php8.3-mbstring php8.3-zip php8.3-gd php8.3-bcmath php8.3-intl php8.3-json php8.3-common -y

Extension purposes:

  • php-cli: Command-line PHP execution
  • php-fpm: FastCGI Process Manager for Nginx
  • php-mysql / php-mysqli / php-pdo: MySQL database connectivity
  • php-curl: Make HTTP requests from PHP code
  • php-xml: XML document processing
  • php-mbstring: Multibyte string handling for international characters
  • php-zip: ZIP archive manipulation
  • php-gd: Image creation and manipulation
  • php-bcmath: Arbitrary precision mathematics
  • php-intl: Internationalization functions
  • php-json: JSON encoding/decoding

Install Extensions for Specific Applications.

Different applications require specific extensions:

WordPress PHP Extensions:

sudo apt install php8.3-mysql php8.3-curl php8.3-gd php8.3-mbstring php8.3-xml php8.3-xmlrpc php8.3-soap php8.3-intl php8.3-zip -y

Laravel PHP Extensions:

sudo apt install php8.3-cli php8.3-fpm php8.3-mysql php8.3-curl php8.3-xml php8.3-mbstring php8.3-zip php8.3-bcmath php8.3-tokenizer php8.3-json php8.3-pdo -y

Drupal PHP Extensions:

sudo apt install php8.3-mysql php8.3-dom php8.3-gd php8.3-json php8.3-pdo php8.3-simplexml php8.3-tokenizer php8.3-xml php8.3-mbstring -y

Magento PHP Extensions:

sudo apt install php8.3-bcmath php8.3-ctype php8.3-curl php8.3-dom php8.3-gd php8.3-hash php8.3-iconv php8.3-intl php8.3-mbstring php8.3-openssl php8.3-pdo php8.3-simplexml php8.3-soap php8.3-xsl php8.3-zip -y

View Installed PHP Extensions.

List all installed PHP modules:

php -m

This displays enabled extensions in your current PHP installation. Use this to verify required extensions are available before deploying applications.

Enable or Disable PHP Extensions.

Debian provides helper tools for managing PHP extensions:

# Enable an extension
sudo phpenmod extension_name

# Disable an extension
sudo phpdismod extension_name

# Example: Enable mysqli extension
sudo phpenmod mysqli

# Example: Disable xdebug extension
sudo phpdismod xdebug

After enabling or disabling extensions, restart your web server or PHP-FPM service to apply changes.

Configuring PHP with Apache Web Server.

Apache remains the most popular web server, and integrating PHP with Apache enables dynamic website hosting.

Step 1: Install Apache Web Server.

If Apache isn’t already installed:

sudo apt install apache2 -y

This installs Apache HTTP Server with default configuration, listening on port 80 for HTTP requests.

Step 2: Install PHP Apache Module.

Install the PHP module for Apache (replace 8.3 with your PHP version):

sudo apt install libapache2-mod-php8.3 -y

This package integrates PHP directly into Apache as a module, allowing Apache to process PHP scripts natively.

Step 3: Enable PHP Module in Apache.

Enable the PHP module if not automatically enabled:

# For PHP 8.3
sudo a2enmod php8.3

# For PHP 8.2
sudo a2enmod php8.2

# For PHP 7.4
sudo a2enmod php7.4

The a2enmod command creates symbolic links to activate Apache modules.

Step 4: Restart Apache Web Server.

Apply configuration changes by restarting Apache:

sudo systemctl restart apache2

Verify Apache is running:

sudo systemctl status apache2

You should see active (running) in green, confirming Apache is operational.

Step 5: Test PHP Processing in Apache.

Create a PHP info file to verify PHP integration:

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

Open your web browser and navigate to:

http://your_server_ip/info.php

Replace your_server_ip with your actual server IP address. You should see a detailed PHP configuration page displaying PHP version, loaded extensions, and configuration settings.

Security Note: Delete this file after testing as it exposes sensitive server information:

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

Configuring PHP Settings for Apache.

Edit PHP configuration file for Apache:

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

Common settings to adjust:

# Increase upload file size limit
upload_max_filesize = 64M
post_max_size = 64M

# Increase memory limit
memory_limit = 256M

# Increase maximum execution time for scripts
max_execution_time = 300

# Increase maximum input time
max_input_time = 300

# Increase maximum input variables
max_input_vars = 3000

# Set timezone
date.timezone = America/New_York

# Disable dangerous functions (security)
disable_functions = exec,passthru,shell_exec,system,proc_open,popen

# Display errors (development only - disable in production)
display_errors = Off
log_errors = On
error_log = /var/log/php/error.log

After making changes, restart Apache:

sudo systemctl restart apache2

Configuring PHP with Nginx Web Server (PHP-FPM).

Nginx doesn’t have built-in PHP support like Apache. Instead, it uses PHP-FPM (FastCGI Process Manager) to process PHP scripts, which often provides better performance under high load.

Step 1: Install Nginx Web Server.

Install Nginx if not already present:

sudo apt install nginx -y

Enable Nginx to start at boot and start the service:

sudo systemctl enable nginx
sudo systemctl start nginx

Step 2: Install PHP-FPM.

Install PHP-FPM for your PHP version:

sudo apt install php8.3-fpm -y

PHP-FPM runs as a separate service from Nginx, managing PHP process pools efficiently.

Step 3: Start and Enable PHP-FPM Service.

Enable PHP-FPM to start automatically at boot:

sudo systemctl enable php8.3-fpm
sudo systemctl start php8.3-fpm

Verify PHP-FPM is running:

sudo systemctl status php8.3-fpm

Step 4: Configure Nginx to Use PHP-FPM.

Edit the default Nginx server block:

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

Add or modify the PHP location block:

server {
    listen 80;
    listen [::]:80;
    
    root /var/www/html;
    index index.php index.html index.htm;
    
    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }

    # PHP processing
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # Deny access to .htaccess files
    location ~ /\.ht {
        deny all;
    }
}

Key configuration points:

  • fastcgi_pass: Points to PHP-FPM socket (change version number to match your installation)
  • location ~ \.php$: Matches all files ending in .php
  • include snippets/fastcgi-php.conf: Includes standard FastCGI configuration

Step 5: Test Nginx Configuration.

Verify configuration syntax:

sudo nginx -t

You should see:

nginx: configuration file /etc/nginx/nginx.conf test is successful

Step 6: Restart Nginx.

Apply configuration changes:

sudo systemctl restart nginx

Step 7: Test PHP Processing with Nginx.

Create a PHP test file:

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

Visit http://your_server_ip/info.php in your browser. You should see the PHP information page, confirming Nginx successfully passes PHP requests to PHP-FPM.

Remove the test file after verification:

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

Configuring PHP-FPM Pool Settings.

PHP-FPM uses pool configurations for better resource management. Edit the www pool:

sudo nano /etc/php/8.3/fpm/pool.d/www.conf

Important settings to optimize:

# User and group PHP-FPM runs as
user = www-data
group = www-data

# Process manager configuration
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500

# Socket configuration (already configured for Nginx)
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

Process manager settings explained:

  • pm.max_children: Maximum number of child processes
  • pm.start_servers: Number of processes created on startup
  • pm.min_spare_servers: Minimum idle processes
  • pm.max_spare_servers: Maximum idle processes
  • pm.max_requests: Number of requests before process restarts (prevents memory leaks)

After changes, restart PHP-FPM:

sudo systemctl restart php8.3-fpm

Configuring PHP Settings for Nginx/PHP-FPM.

Edit PHP-FPM’s php.ini file:

sudo nano /etc/php/8.3/fpm/php.ini

Apply the same PHP configuration changes mentioned in the Apache section. After editing, restart PHP-FPM:

sudo systemctl restart php8.3-fpm

Installing PHP Composer (Dependency Manager).

Composer is PHP’s dependency manager, essential for modern PHP development and frameworks like Laravel, Symfony, and Drupal.

Step 1: Download Composer Installer.

Download the official Composer installer:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

Step 2: Verify Installer Integrity.

Verify the installer’s SHA-384 hash matches the official checksum:

HASH="$(wget -q -O - https://composer.github.io/installer.sig)"
php -r "if (hash_file('sha384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

You should see “Installer verified”, confirming the download is authentic.

Step 3: Install Composer Globally.

Install Composer system-wide:

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

Step 4: Remove Installer.

Clean up the installer file:

php -r "unlink('composer-setup.php');"

Step 5: Verify Composer Installation.

Check Composer installation:

composer --version

Output shows Composer version:

Composer version 2.7.1 2024-02-09 15:26:28

Composer is now ready for managing PHP project dependencies.

Creating a Simple PHP Application.

Let’s create a basic PHP application to test our complete setup.

Create Project Directory.

sudo mkdir -p /var/www/html/myapp
cd /var/www/html/myapp

Create a Simple PHP Script.

Create index.php:

sudo nano /var/www/html/myapp/index.php

Add this sample code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Test Application</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
        }
        .info-box {
            background: #f4f4f4;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>PHP Test Application</h1>
    
    <div class="info-box">
        <h2>Server Information</h2>
        <p><strong>PHP Version:</strong> <?php echo phpversion(); ?></p>
        <p><strong>Server Software:</strong> <?php echo $_SERVER['SERVER_SOFTWARE']; ?></p>
        <p><strong>Document Root:</strong> <?php echo $_SERVER['DOCUMENT_ROOT']; ?></p>
    </div>

    <div class="info-box">
        <h2>Loaded PHP Extensions</h2>
        <ul>
            <?php foreach(get_loaded_extensions() as $extension): ?>
                <li><?php echo $extension; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>

    <div class="info-box">
        <h2>Current Date and Time</h2>
        <p><?php echo date('l, F j, Y - H:i:s'); ?></p>
    </div>
</body>
</html>

Set Proper Permissions.

Ensure web server can read files:

sudo chown -R www-data:www-data /var/www/html/myapp
sudo chmod -R 755 /var/www/html/myapp

Access Your Application.

Visit http://your_server_ip/myapp/ in your browser. You should see your PHP application displaying server information, loaded extensions, and current date/time.

PHP Security Best Practices on Debian.

Security should be a top priority when running PHP applications on production servers.

1. Disable Dangerous PHP Functions.

Edit php.ini to disable potentially dangerous functions:

disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

These functions can be exploited for remote code execution if vulnerabilities exist in your application.

2. Hide PHP Version Information.

Prevent PHP from sending version information in HTTP headers:

expose_php = Off

This makes it harder for attackers to target version-specific vulnerabilities.

3. Configure Error Reporting Properly.

Never display errors in production:

# Production settings
display_errors = Off
log_errors = On
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
error_log = /var/log/php/error.log

Create the log directory:

sudo mkdir -p /var/log/php
sudo chown www-data:www-data /var/log/php

4. Restrict File Operations.

Limit where PHP can read and write files:

open_basedir = /var/www:/tmp:/var/tmp

This restricts PHP file operations to specified directories, preventing access to sensitive system files.

5. Disable URL File Access.

Prevent PHP from accessing remote files via URL:

allow_url_fopen = Off
allow_url_include = Off

This blocks common attack vectors where malicious code is included from external URLs.

6. Set Session Security.

Configure secure session handling:

session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1
session.cookie_samesite = "Strict"

These settings protect session cookies from XSS attacks and CSRF vulnerabilities.

7. Enable OPcache for Performance and Security.

OPcache improves performance and can help prevent some attacks:

opcache.enable = 1
opcache.memory_consumption = 128
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 4000
opcache.validate_timestamps = 0
opcache.revalidate_freq = 60

After making security changes, restart your web server or PHP-FPM.

Troubleshooting Common PHP Installation Issues.

Issue 1: PHP Not Processing (Showing Source Code).

Symptom: Browser displays PHP code instead of executing it.

Solution for Apache:

# Verify PHP module is enabled
sudo a2enmod php8.3
sudo systemctl restart apache2

Solution for Nginx:

# Verify PHP-FPM is running
sudo systemctl status php8.3-fpm

# Check Nginx configuration
sudo nginx -t

# Verify socket path in Nginx config matches PHP-FPM

Issue 2: PHP Extension Not Loading.

Symptom: Functions from an extension return “undefined function” errors.

Solution:

# Verify extension is installed
php -m | grep extension_name

# Install if missing
sudo apt install php8.3-extension_name

# Enable the extension
sudo phpenmod extension_name

# Restart web server
sudo systemctl restart apache2  # or php8.3-fpm for Nginx

Issue 3: Permission Denied Errors.

Symptom: PHP cannot read or write files.

Solution:

# Set correct ownership
sudo chown -R www-data:www-data /var/www/html

# Set appropriate permissions
sudo chmod -R 755 /var/www/html

# For upload directories
sudo chmod -R 775 /var/www/html/uploads

Issue 4: Memory Limit Exhausted.

Symptom: “Allowed memory size exhausted” errors.

Solution: Edit php.ini and increase memory limit:

memory_limit = 256M

Restart web server or PHP-FPM after changes.

Issue 5: Maximum Execution Time Exceeded.

Symptom: Scripts timeout before completing.

Solution: Edit php.ini:

max_execution_time = 300
max_input_time = 300

Restart services after changes.

Issue 6: File Upload Size Limits.

Symptom: Large file uploads fail.

Solution: Edit php.ini:

upload_max_filesize = 100M
post_max_size = 100M

Note: post_max_size should be larger than upload_max_filesize.

Upgrading PHP to Newer Versions.

When new PHP versions are released, upgrading ensures you benefit from performance improvements and security patches.

Step 1: Backup Current Configuration.

Before upgrading, backup your PHP configuration:

sudo cp -r /etc/php /etc/php.backup

Step 2: Install New PHP Version.

Install the newer PHP version alongside the current one:

sudo apt update
sudo apt install php8.4 php8.4-fpm php8.4-mysql php8.4-curl php8.4-xml php8.4-mbstring php8.4-zip php8.4-gd -y

Step 3: Switch Apache to New PHP Version.

For Apache:

# Disable old version
sudo a2dismod php8.3

# Enable new version
sudo a2enmod php8.4

# Restart Apache
sudo systemctl restart apache2

Step 4: Switch Nginx to New PHP-FPM.

For Nginx, update server block configuration:

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

Change:

fastcgi_pass unix:/run/php/php8.4-fpm.sock;

Restart services:

sudo systemctl restart php8.4-fpm
sudo systemctl restart nginx

Step 5: Migrate Configuration.

Copy customized settings from old php.ini to new:

# Compare configurations
diff /etc/php/8.3/fpm/php.ini /etc/php/8.4/fpm/php.ini

# Manually migrate your custom settings
sudo nano /etc/php/8.4/fpm/php.ini

Step 6: Test Thoroughly.

Test all applications thoroughly with the new PHP version before removing the old one.

Step 7: Remove Old PHP Version (Optional).

Once confident the new version works correctly:

sudo apt purge php8.3* -y
sudo apt autoremove -y

Monitoring PHP Performance.

Install PHP-FPM Status Page.

Enable PHP-FPM status monitoring:

sudo nano /etc/php/8.3/fpm/pool.d/www.conf

Add or uncomment:

pm.status_path = /status

Configure Nginx to access the status page:

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

Add this location block:

location ~ ^/(status|ping)$ {
    access_log off;
    allow 127.0.0.1;
    deny all;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}

Restart services:

sudo systemctl restart php8.3-fpm
sudo systemctl restart nginx

View PHP-FPM status:

curl http://localhost/status

Output shows active processes, idle processes, total processes, and request statistics.

Monitor PHP Error Logs.

Regularly check PHP error logs for issues:

# View PHP-FPM error log
sudo tail -f /var/log/php8.3-fpm.log

# View PHP application errors
sudo tail -f /var/log/php/error.log

# Search for specific errors
sudo grep "Fatal error" /var/log/php/error.log

Use System Monitoring Tools.

Install monitoring utilities:

sudo apt install htop iotop nethogs -y

Monitor PHP-FPM processes:

# View PHP-FPM processes
ps aux | grep php-fpm

# Monitor resource usage with htop
htop

# Monitor PHP-FPM specifically
htop -p $(pgrep -d',' php-fpm)

Optimizing PHP Performance on Debian.

Enable OPcache.

OPcache stores precompiled script bytecode in memory, dramatically improving performance:

# Verify OPcache is installed
php -m | grep -i opcache

# If not installed
sudo apt install php8.3-opcache -y

Configure OPcache settings in php.ini:

[opcache]
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1

OPcache settings explained:

  • memory_consumption: Memory allocated to OPcache (128MB recommended)
  • max_accelerated_files: Maximum number of cached scripts
  • revalidate_freq: How often to check for script changes (seconds)
  • fast_shutdown: Faster shutdown sequence
  • enable_cli: Enable for CLI scripts (useful for testing)

Configure Realpath Cache.

Realpath cache reduces filesystem stat calls:

realpath_cache_size = 4096K
realpath_cache_ttl = 600

Optimize PHP-FPM Process Management.

Tune PHP-FPM based on available RAM:

For servers with 4GB RAM:

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 20
pm.max_requests = 500

For servers with 8GB RAM:

pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 40
pm.max_requests = 500

Calculate pm.max_children:

Average PHP process memory = 30MB (check with: ps aux | grep php-fpm)
Available RAM for PHP = 2GB (example)
pm.max_children = 2000MB / 30MB ≈ 66 processes

Always leave RAM for MySQL, Nginx/Apache, and system processes.

Enable PHP-FPM Slow Log.

Track slow PHP scripts:

slowlog = /var/log/php/php-fpm-slow.log
request_slowlog_timeout = 5s

This logs any request taking longer than 5 seconds, helping identify performance bottlenecks.

Using PHP with MySQL/MariaDB Database.

Most PHP applications require database connectivity. Let’s set up MySQL/MariaDB with PHP.

Install MySQL or MariaDB.

Choose one database server:

Install MariaDB (recommended):

sudo apt install mariadb-server -y

Or install MySQL:

sudo apt install mysql-server -y

Secure Database Installation.

Run security script:

sudo mysql_secure_installation

Follow prompts to:

  • Set root password
  • Remove anonymous users
  • Disallow root remote login
  • Remove test database
  • Reload privilege tables

Install PHP MySQL Extensions.

Install required PHP extensions for database connectivity:

sudo apt install php8.3-mysql php8.3-mysqli -y

Restart web server or PHP-FPM:

sudo systemctl restart php8.3-fpm

Test PHP Database Connection.

Create a test script:

sudo nano /var/www/html/db-test.php

Add this code:

<?php
$servername = "localhost";
$username = "your_db_username";
$password = "your_db_password";
$database = "your_database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to MySQL database!";
echo "<br>MySQL version: " . $conn->server_info;

$conn->close();
?>

Access http://your_server_ip/db-test.php to verify connectivity.

Important: Delete this test file after verification:

sudo rm /var/www/html/db-test.php

Create Database and User for PHP Application.

Log into MySQL:

sudo mysql -u root -p

Create database and user:

CREATE DATABASE myapp_db;
CREATE USER 'myapp_user'@'localhost' IDENTIFIED BY 'secure_password_here';
GRANT ALL PRIVILEGES ON myapp_db.* TO 'myapp_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Your PHP applications can now connect using these credentials.

Installing Popular PHP Applications.

Installing WordPress on Debian with PHP.

Step 1: Install prerequisites:

sudo apt install php8.3-mysql php8.3-curl php8.3-gd php8.3-mbstring php8.3-xml php8.3-xmlrpc php8.3-soap php8.3-intl php8.3-zip -y

Step 2: Create database:

sudo mysql -u root -p
CREATE DATABASE wordpress_db;
CREATE USER 'wp_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON wordpress_db.* TO 'wp_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Step 3: Download WordPress:

cd /tmp
wget https://wordpress.org/latest.tar.gz
tar -xvzf latest.tar.gz
sudo cp -r wordpress /var/www/html/

Step 4: Set permissions:

sudo chown -R www-data:www-data /var/www/html/wordpress
sudo chmod -R 755 /var/www/html/wordpress

Step 5: Complete installation via browser at http://your_server_ip/wordpress

Installing Laravel on Debian with PHP.

Step 1: Ensure Composer is installed (covered earlier)

Step 2: Install required PHP extensions:

sudo apt install php8.3-cli php8.3-fpm php8.3-mysql php8.3-curl php8.3-xml php8.3-mbstring php8.3-zip php8.3-bcmath php8.3-tokenizer -y

Step 3: Create Laravel project:

cd /var/www/html
sudo composer create-project laravel/laravel mylaravelapp

Step 4: Set permissions:

sudo chown -R www-data:www-data /var/www/html/mylaravelapp
sudo chmod -R 775 /var/www/html/mylaravelapp/storage
sudo chmod -R 775 /var/www/html/mylaravelapp/bootstrap/cache

Step 5: Configure Nginx for Laravel:

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

Add:

server {
    listen 80;
    server_name your_domain.com;
    root /var/www/html/mylaravelapp/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Step 6: Enable site and restart Nginx:

sudo ln -s /etc/nginx/sites-available/laravel /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Setting Up SSL/TLS for PHP Applications.

Secure your PHP applications with HTTPS using Let’s Encrypt free SSL certificates.

Install Certbot.

sudo apt install certbot python3-certbot-nginx -y

Or for Apache:

sudo apt install certbot python3-certbot-apache -y

Obtain SSL Certificate for Nginx.

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

Obtain SSL Certificate for Apache.

sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

Follow prompts to enter email and agree to terms. Certbot automatically configures SSL and sets up HTTP to HTTPS redirect.

Auto-Renewal.

Test automatic renewal:

sudo certbot renew --dry-run

Certificates automatically renew every 90 days through systemd timer.

Verify SSL Configuration.

Check your SSL setup at: https://www.ssllabs.com/ssltest/

PHP Development Tools for Debian.

Install Xdebug for PHP Debugging.

Xdebug is essential for development and debugging:

sudo apt install php8.3-xdebug -y

Configure Xdebug:

sudo nano /etc/php/8.3/mods-available/xdebug.ini

Add configuration:

zend_extension=xdebug.so
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.log=/var/log/xdebug.log

Restart PHP-FPM:

sudo systemctl restart php8.3-fpm

Install PHP CodeSniffer for Code Quality.

Install PHPCS for coding standards:

composer global require "squizlabs/php_codesniffer=*"

Add to PATH:

echo 'export PATH="$PATH:$HOME/.config/composer/vendor/bin"' >> ~/.bashrc
source ~/.bashrc

Check code:

phpcs --standard=PSR12 /path/to/your/code

Install PHPUnit for Testing.

Install PHPUnit via Composer:

composer global require phpunit/phpunit

Create simple test:

<?php
use PHPUnit\Framework\TestCase;

class SimpleTest extends TestCase
{
    public function testAddition()
    {
        $this->assertEquals(4, 2 + 2);
    }
}

Run tests:

phpunit SimpleTest.php

Backing Up PHP Configuration.

Regular backups prevent configuration loss during upgrades or system failures.

Backup PHP Configuration Files.

Create backup script:

sudo nano /usr/local/bin/backup-php-config.sh

Add:

#!/bin/bash
BACKUP_DIR="/backup/php-config"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $BACKUP_DIR

# Backup PHP configurations
tar -czf $BACKUP_DIR/php-config-$DATE.tar.gz /etc/php/

# Backup web server configs
tar -czf $BACKUP_DIR/nginx-config-$DATE.tar.gz /etc/nginx/
# Or for Apache: tar -czf $BACKUP_DIR/apache-config-$DATE.tar.gz /etc/apache2/

# Keep only last 7 days of backups
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete

echo "Backup completed: $DATE"

Make executable:

sudo chmod +x /usr/local/bin/backup-php-config.sh

Automate Backups with Cron

Schedule daily backups:

sudo crontab -e

Add:

0 2 * * * /usr/local/bin/backup-php-config.sh

This runs backup daily at 2:00 AM.

Uninstalling PHP from Debian.

If you need to remove PHP completely:

Remove Specific PHP Version.

# Remove PHP 8.3 and all extensions
sudo apt purge php8.3* -y

# Remove orphaned packages
sudo apt autoremove -y

# Remove configuration files
sudo rm -rf /etc/php/8.3

Remove All PHP Versions.

# Remove all PHP packages
sudo apt purge 'php*' -y

# Clean up
sudo apt autoremove -y
sudo apt autoclean

# Remove PHP configurations
sudo rm -rf /etc/php

Remove Ondřej Surý Repository.

# Remove repository
sudo rm /etc/apt/sources.list.d/php.list

# Remove GPG key
sudo rm /etc/apt/trusted.gpg.d/php.gpg

# Update package lists
sudo apt update

Frequently Asked Questions (FAQ).

What PHP version should I install on Debian 12?

For Debian 12 (Bookworm), PHP 8.2 is the default. However, for new projects, install PHP 8.3 or PHP 8.4 using the Ondřej Surý repository for the latest features, performance improvements, and long-term support.

Can I run multiple PHP versions simultaneously on Debian?

Yes, you can install multiple PHP versions side-by-side using the Ondřej Surý repository. Each version runs independently through different PHP-FPM pools, allowing different applications to use different PHP versions on the same server.

Should I use PHP with Apache or Nginx?

Both work excellently. Apache with mod_php is simpler to configure and great for shared hosting. Nginx with PHP-FPM typically provides better performance under high traffic loads and uses fewer resources. For most modern applications, Nginx + PHP-FPM is recommended.

How do I check which PHP extensions are installed?

Use the command php -m to list all installed and enabled PHP modules. For web server PHP, create a phpinfo() file to see extensions loaded in the web environment.

Why isn’t my PHP code executing?

Common causes include:

  1. PHP module not enabled in Apache (sudo a2enmod php8.3).
  2. PHP-FPM not running for Nginx (sudo systemctl status php8.3-fpm).
  3. Incorrect file permissions.
  4. Web server configuration not processing .php files.
  5. PHP files have incorrect extensions.

How much RAM does PHP need?

Minimum 512MB for basic sites, 2-4GB for WordPress or small applications, 8GB+ for Laravel or high-traffic sites. Each PHP-FPM process typically uses 25-50MB RAM. Calculate requirements based on expected concurrent requests.

How do I update PHP to the latest version?

Add the Ondřej Surý repository, install the new PHP version, switch your web server configuration to use the new version, test thoroughly, and remove the old version once confirmed working.

Is PHP secure on Debian?

Yes, when properly configured. Follow security best practices: disable dangerous functions, hide PHP version, configure proper error reporting, restrict file operations, keep PHP updated, and use strong passwords for database connections.

Can I use PHP for command-line scripts?

Absolutely. PHP CLI (Command Line Interface) is perfect for cron jobs, automation scripts, and background tasks. Just make sure you install php-cli package and run scripts with php script.php.

How do I troubleshoot PHP memory limit errors?

Edit php.ini and increase memory_limit = 256M (or higher based on needs). Remember to restart Apache or PHP-FPM after changes. For specific scripts, use ini_set('memory_limit', '512M'); at the script start.

Conclusion.

Installing and configuring PHP on Debian provides a powerful foundation for web development, hosting dynamic websites, and running modern web applications. This comprehensive guide covered everything from basic PHP installation using default repositories to advanced configurations with multiple PHP versions, performance optimization, security hardening, and integration with Apache or Nginx web servers.

Key Takeaways:

  • Debian offers stable PHP packages through default repositories, perfect for production servers valuing reliability over bleeding-edge features
  • Ondřej Surý repository provides current PHP versions including PHP 8.3 and PHP 8.4 for developers needing modern features
  • Multiple PHP versions can coexist on the same system, allowing different applications to use appropriate PHP versions
  • PHP-FPM with Nginx typically outperforms Apache mod_php in high-traffic scenarios, though both configurations work excellently
  • Security configuration is essential including disabling dangerous functions, hiding version information, and proper error handling
  • Performance optimization through OPcache and proper PHP-FPM tuning significantly improves application response times
  • Regular updates and monitoring ensure your PHP installation remains secure and performs optimally

Whether you’re deploying WordPress, Laravel, Drupal, or custom PHP applications, Debian provides the stable, secure, and efficient platform you need.

The combination of Debian’s reliability and PHP’s flexibility creates an excellent environment for web hosting and development.

Remember to regularly update your system (by using command: sudo apt update && sudo apt upgrade), monitor PHP logs for issues, back up configurations before making changes, and follow security best practices to keep your PHP applications safe and performant.

Start your PHP journey on Debian today, and you’ll have a robust platform capable of powering everything from simple websites to complex enterprise applications.

The skills you’ve learned in this guide apply across PHP development, system administration, and web hosting—knowledge that remains valuable throughout your technical career. Happy coding, and may your uptime be eternal!

Leave a Reply

Your email address will not be published. Required fields are marked *