Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

How to Install PHP GD Extension on Ubuntu 24.04 LTS

Published

PHP

PHP GD extension is essential for image processing tasks in web development. This guide provides step-by-step instructions for installing and configuring the PHP GD extension on an Ubuntu 24.04 LTS system.

What is PHP GD Extension

The PHP GD extension is a powerful graphics library integrated with PHP. It provides a set of tools and functions for creating, editing, converting, and displaying images directly from PHP scripts. This makes tasks such as processing user-uploaded photos, generating captchas, or building graphs and charts much more manageable.

Key Features:

  • Image resizing and cropping
  • Dynamic image generation
  • Text rendering on images
  • Image format conversion
  • Watermark addition
  • Thumbnail creation

Why is the PHP GD Extension Important?

Many content management systems (CMS) such as WordPress, Drupal, and Joomla depend on the GD extension for image-related operations. Without GD, features like image uploads, avatar generation, and media editing may not work correctly.

Furthermore, GD is used in numerous open-source PHP scripts and libraries, making it a near-essential utility for most PHP hosting environments.

Prerequisites

Before starting the installation process, ensure you have:

  • Ubuntu 24.04 LTS server or desktop
  • Root or sudo access
  • PHP installed on your system
  • Active internet connection

Check Current PHP Installation

First, verify the PHP installation and version on your system:

php -v

If PHP is not installed, install it using:

sudo apt update
sudo apt install php php-cli

Verify GD Extension Status

Check if the GD extension is already installed:

php -m | grep -i gd

You can also use PHP code to check:

php -r "if(extension_loaded('gd')) echo 'GD is installed'; else echo 'GD not found';"

Installation Steps

Step 1: Update System Packages

Update your package repository to ensure the latest versions:

sudo apt update
sudo apt upgrade -y

Step 2: Install PHP GD Extension

For PHP 8.3 (default in Ubuntu 24.04):

sudo apt install php8.3-gd

For other PHP versions:

# PHP 8.2
sudo apt install php8.2-gd

# PHP 8.1
sudo apt install php8.1-gd

# Generic installation (auto-detects version)
sudo apt install php-gd

Step 3: Install Supporting Libraries

Install additional image processing libraries for enhanced functionality:

sudo apt install libjpeg-dev libpng-dev libfreetype6-dev libwebp-dev libxpm-dev

These libraries provide:

  • libjpeg-dev: JPEG image support
  • libpng-dev: PNG image support
  • libfreetype6-dev: TrueType font support
  • libwebp-dev: WebP format support
  • libxpm-dev: XPM format support

Step 4: Restart Web Server

Restart your web server to load the new extension:

For Apache:

sudo systemctl restart apache2

For Nginx with PHP-FPM:

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

For development server:

sudo service apache2 restart

Verification and Testing

Method 1: Command Line Verification

Check if the GD extension is loaded:

php -m | grep -i gd

Get detailed GD information:

php -r "print_r(gd_info());"

Method 2: Create PHP Info File

Create a test file to check through the browser:

sudo nano /var/www/html/phpinfo.php

Add the following content:

<?php
phpinfo();
?>

Visit http://your-server-ip/phpinfo.php and search for the “gd” section.

Method 3: GD Functionality Test

Create a test script to verify GD functionality:

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

Add this code:

<?php
if (extension_loaded('gd')) {
    echo "PHP GD Extension: ENABLED<br>";
    echo "GD Version: " . gd_info()['GD Version'] . "<br><br>";
    
    echo "Supported Image Formats:<br>";
    $gd_info = gd_info();
    
    if ($gd_info['JPEG Support']) echo "✓ JPEG Support<br>";
    if ($gd_info['PNG Support']) echo "✓ PNG Support<br>";
    if ($gd_info['GIF Read Support']) echo "✓ GIF Support<br>";
    if ($gd_info['WebP Support']) echo "✓ WebP Support<br>";
    if ($gd_info['FreeType Support']) echo "✓ FreeType Support<br>";
    
} else {
    echo "PHP GD Extension: NOT INSTALLED";
}
?>

Create Test Image

Test image creation functionality with this script:

<?php
// Create a 400x200 image
$image = imagecreate(400, 200);

// Define colors
$background = imagecolorallocate($image, 255, 255, 255); // White
$text_color = imagecolorallocate($image, 0, 0, 0);       // Black
$border_color = imagecolorallocate($image, 200, 200, 200); // Gray

// Add border
imagerectangle($image, 0, 0, 399, 199, $border_color);

// Add text
imagestring($image, 5, 120, 90, 'GD Extension Working!', $text_color);

// Set content type and output image
header('Content-Type: image/png');
imagepng($image);

// Clean up memory
imagedestroy($image);
?>

Common Installation Issues and Solutions

Issue 1: Package Not Found

Problem: E: Unable to locate package php-gd

Solution:

sudo apt update
sudo apt-cache search php | grep gd
sudo apt install php-gd

Issue 2: Multiple PHP Versions

Problem: GD installed but not working

Solution: Install for specific PHP version:

# Check active PHP version
php -v

# Install for specific version
sudo apt install php8.3-gd

Issue 3: Web Server Not Loading Extension

Problem: Works in CLI but not in web browser

Solution:

  • Check the PHP version used by a web server
  • Restart the web server after installation
  • Verify correct php.ini file is being used

Issue 4: Permission Errors

Problem: Cannot create or modify images

Solution:

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

PHP Configuration Optimization

Memory Limit

For image processing, increase the PHP memory limit in /etc/php/8.3/apache2/php.ini:

memory_limit = 256M

File Upload Limits

If processing uploaded images:

upload_max_filesize = 50M
post_max_size = 50M
max_execution_time = 300

GD Configuration

Enable specific GD features:

extension=gd

Security Considerations

File Type Validation

Always validate uploaded image files:

$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
$file_type = mime_content_type($_FILES['image']['tmp_name']);

if (!in_array($file_type, $allowed_types)) {
    die('Invalid file type');
}

File Size Limits

Implement file size restrictions:

$max_size = 5 * 1024 * 1024; // 5MB
if ($_FILES['image']['size'] > $max_size) {
    die('File too large');
}

Performance Tips

Image Optimization

Use appropriate image quality settings:

// JPEG with 85% quality
imagejpeg($image, 'output.jpg', 85);

// PNG with compression level 6
imagepng($image, 'output.png', 6);

Memory Management

Always destroy images after processing:

imagedestroy($image);

Batch Processing

For multiple images, process in batches to avoid memory issues:

$images = glob('*.jpg');
$batch_size = 10;

for ($i = 0; $i < count($images); $i += $batch_size) {
    $batch = array_slice($images, $i, $batch_size);
    // Process batch
    gc_collect_cycles(); // Force garbage collection
}

Troubleshooting Commands

Useful commands for debugging GD issues:

# Check PHP modules
php -m

# Check PHP configuration
php --ini

# Test specific function
php -r "var_dump(function_exists('imagecreate'));"

# Check error logs
sudo tail -f /var/log/apache2/error.log

# Verify package installation
dpkg -l | grep php-gd

Uninstallation (If Needed)

To remove the PHP GD extension:

sudo apt remove php-gd
sudo systemctl restart apache2

Conclusion

Installing the PHP GD extension on Ubuntu 24.04 is straightforward when following the proper steps. The extension provides essential image processing capabilities for modern web applications. Regular testing and proper configuration ensure optimal performance and security.

Key points to remember:

  • Always update system packages before installation
  • Restart the web server after installation
  • Verify installation through multiple methods
  • Configure PHP settings for optimal performance
  • Implement security measures for file uploads

With PHP GD properly installed and configured, you can now build robust image processing features into your PHP applications.

Related guides

Account services are unavailable until the production backend is configured.