Development

How to Resize Uploaded Images With PHP

Resizing an uploaded image in PHP means decoding a validated image, calculating bounded output dimensions, resampling its pixels, and writing a new file. File size alone does not bound the memory needed to decode an image.

This example uses PHP 8.1 or newer with GD and JPEG support. It accepts an already validated JPEG path in private storage. Authentication, CSRF protection, upload limits, and ownership belong to the upload endpoint that calls it.

Resize uploaded images with bounded dimensions

A compressed photograph can expand into millions of pixels. Check dimensions before decoding, and apply both a compressed-byte limit at upload and a pixel limit here. The limits below are application policy examples, not a guarantee that every host has enough memory.

<?php

declare(strict_types=1);

/** Write a bounded JPEG derivative without enlarging the source. */
function resizeJpeg(string $source, string $destination, int $maxWidth = 1200): void
{
    if ($maxWidth < 1 || $maxWidth > 2400) {
        throw new InvalidArgumentException('Invalid output width.');
    }
    $info = getimagesize($source);
    if ($info === false || $info[2] !== IMAGETYPE_JPEG) {
        throw new RuntimeException('A JPEG image is required.');
    }
    [$width, $height] = $info;
    if ($width < 1 || $height < 1 || $width > 8000 || $height > 8000
        || $width * $height > 16000000) {
        throw new RuntimeException('Image dimensions exceed the policy.');
    }
    $targetWidth = min($width, $maxWidth);
    $targetHeight = max(1, (int) round($height * $targetWidth / $width));
    $input = imagecreatefromjpeg($source);
    if ($input === false) {
        throw new RuntimeException('JPEG decoding failed.');
    }
    $output = imagecreatetruecolor($targetWidth, $targetHeight);
    if ($output === false) {
        throw new RuntimeException('Output allocation failed.');
    }
    if (!imagecopyresampled($output, $input, 0, 0, 0, 0,
        $targetWidth, $targetHeight, $width, $height)) {
        throw new RuntimeException('Image resampling failed.');
    }
    if (!imagejpeg($output, $destination, 85)) {
        throw new RuntimeException('JPEG export failed.');
    }
}

PHP documents the scaling operation in imagecopyresampled. Keep warnings in server logs and return a generic processing error to the user. Do not display private filesystem paths in a response.

Choose the output policy before handling formats

This function deliberately handles JPEG only. Transparent PNGs require an alpha-preservation policy, while animated GIFs require a decision about retaining animation. Sending every input through a JPEG encoder can discard information the user expected to keep.

Phone photographs can contain an EXIF orientation flag. This example resizes the stored pixels and does not apply EXIF rotation. For a production photo workflow, normalize orientation before calculating final dimensions, and test all orientation values with known fixtures. Do not silently claim correct phone-photo orientation from a width and height check.

Keep uploaded originals private, use random storage names, and map derivatives to an owner in your database. A derivative filename supplied by the browser is not a safe destination path. Write to a temporary file on the same filesystem and rename it into place only after export succeeds, so readers never see a partial image.

Bound work as well as output

A small output does not make decoding cheap. Limit concurrent image jobs and request frequency. A busy site should process derivatives in a bounded worker and expose a pending state until the result exists. Untrusted image processing may also warrant a separately constrained process, depending on the deployment.

Set file permissions through your deployment policy. Keep the output directory non-executable and serve generated images with an explicit image content type. Neither resizing nor metadata removal replaces an access check for private photographs.

What should I test?

Use fixtures for a landscape JPEG, portrait JPEG, image smaller than the target, corrupt image, and image exceeding the pixel limit. Check actual output dimensions, visual orientation, file type, and error handling. Test under the worker's real memory limit rather than assuming the CLI and web server share a configuration.

For responsive HTML, create only the widths your templates use and include intrinsic dimensions to reserve layout space. The performance discussion in PHP performance bottlenecks explains why a smaller asset still needs a measured delivery path.

Need help turning an upload handler into a dependable media pipeline? Discuss a focused PHP review.