Image uploads: size, type, metadata, and safe processing

Separate byte intake, geometry checks, decoding, and normalization: private quarantine, EXIF orientation, and the boundaries of resource limits.

Accepting an image combines checking the incoming bytes with producing a separate normalized result.

An editor selects a photograph, sees the expected extension, and clicks Upload. The interface presents one action. Inside the server, that action contains several different questions: how many bytes may be accepted, what the file actually contains, how much memory the decoder needs, and which result can be delivered to a reader.

A small file does not necessarily mean a small image. A correct signature does not prove that all the data can be decoded. Removing metadata can also turn a photograph sideways if its orientation has not yet been applied to the pixels. We will build an acceptance sequence in which each check has a defined responsibility.

First define what “accepted” means

In the previous media asset model, a source revision was already a known set of bytes. Now consider the preceding stage: an untrusted file must pass inspection and normalization. Its presence on disk alone does not create a usable cover.

Continue one article_demo on Symfony 8.1 and 64-bit PHP 8.4+: add src/ImageAcceptance, AcceptImageCommand, and tests. Use Linux, GD with JPEG/PNG, EXIF, fileinfo, zlib, and proc_open. An earlier step already added native Symfony Process. An operator-selected local file produces a private directory containing a normalized PNG and receipt. This is the stage after receiving bytes rather than a complete HTTP-upload endpoint.

The exercise allows static JPEG and PNG. GIF, SVG, WebP, and other formats are unsupported here. That is a narrow product policy, not a judgment that every other format is dangerous. Each additional format needs its own decisions about decoding, animation, metadata, and resource limits.

Three limits instead of one number

A byte limit bounds the incoming stream and the space needed for its private copy. Width and height limits reject unacceptable geometry. A total pixel limit bounds the area that decoding will expand. None of these values, by itself, describes the process's maximum memory consumption.

Layer Exercise policy What it bounds
Input bytes 2 MiB The private copy before the decoder starts
Image side 4096 pixels Excessive width or height
Area 4 000 000 pixels An image whose individual sides fit the limit but whose area is too large
Normalized output 20 MiB The acceptable size of the generated file

These are parameters of the teaching example, not universal recommendations for every photograph. Check the geometry again after rotation. To avoid relying on multiplication of potentially large values, the area check can use division:

if ($width > intdiv(Policy::MAX_PIXELS, $height)) {
    throw new \RuntimeException('pixel_limit');
}

Before this check, height must already be positive and within the side limit. Pixel processing needs memory for the decoded image, its rotated version, a new canvas, and temporary library structures. The process budget therefore needs checking on the chosen build; it cannot be derived solely from JPEG file size.

The content must confirm the file type

The name photo.jpg and a client-supplied Content-Type are not evidence. OWASP recommends combining allowed-format restrictions, content checks, application-generated storage names, and storage outside the webroot. Rewriting an image also does not remove the risks of the decoder itself.

In this exercise, finfo identifies MIME from the bytes, and the header must then agree with an allowed type. getimagesize() supplies preliminary geometry; PHP explicitly warns that this function does not validate an image. Actual decoding with an allowed GD decoder must follow.

For PNG, the example also checks chunk structure and checksums. This is an additional check before the decoder. Our narrow policy rejects PNG animation and PNG containing an EXIF chunk, avoiding silent frame loss or ignored, unsupported orientation.

The decoder reads a private, stable copy

The command first creates its own randomly named quarantine directory. The user's filename does not determine the storage path. It copies no more than the configured byte limit plus one byte: enough to detect an excess without copying the entire oversized file.

Analysis starts only after the copy has been closed. Every later check and the source fingerprint refer to those same bytes. Reopening the original path at each stage could produce different content if the source changed between operations.

The exercise directories belong to one operator, and unrelated processes must not modify them. The command does not download URLs or accept arbitrary paths from web requests. A future HTTP adapter must receive a server-side upload path and separately check upload completion and user permissions.

The private-copy limit applies after the server has received the file. It does not protect the preceding upload directory from filling up or reject an excessive HTTP body at ingress. A web workflow must coordinate request limits at the entry point with PHP upload settings, including upload_max_filesize and post_max_size. This command exercise does not check that transport layer.

Orientation must survive metadata removal

A camera may store pixels in one direction and record the intended display in EXIF. Discarding that record first leaves the decoded raster incorrectly rotated. For JPEG, therefore, read EXIF through PHP, apply the orientation, and only then create the new raster.

The example covers all eight orientation values, including reflections. These cannot be reduced to swapping width and height: two rotations can have identical dimensions but put the content in different positions. An asymmetric fixture and checks of colored region positions are needed.

Pixels are copied onto the new canvas; the original file is not. The result is encoded as PNG without carrying over source EXIF, text comments, or color profiles. Colorimetric equivalence is not guaranteed here: professional workflows need separate profile handling. PNG transparency is preserved explicitly.

A separate process has limits, but it is not an isolation boundary

Decoding runs in a child PHP process through Symfony Process. Arguments are passed as an array rather than a constructed shell string. The exercise sets an overall timeout of 5 seconds and PHP memory_limit=128M, without accumulating child process output.

Those limits do not constitute a full sandbox. The child still runs with the same user's permissions and inherits access to the environment. The GD documentation also warns that a system build of the library may allocate memory outside PHP's memory_limit.

Processing a real untrusted stream needs operating-system limits on memory, CPU, disk, process counts, file access, and network access. Updated decoders and limits on concurrent jobs are also needed. The teaching process demonstrates dispatch and failure handling, but does not configure those system mechanisms.

Accept a checked result, not a successful function call

Even a true return value from the encoder is insufficient. The imagepng() documentation describes a case in which a libgd output failure is not reflected in the return value. After writing, the example therefore checks that the new file exists, is nonempty, and has the expected format, geometry, and structure.

The receipt contains an application-generated identifier, dimensions, type, byte counts, and fingerprints of both source and output. The image and receipt are first prepared together in a private directory. Only then is the whole directory renamed into accepted on the same filesystem. That creates a local visibility boundary; it is neither a database transaction nor proof of durability after a power failure.

Quarantine is cleaned after normal completion or a caught error. An abrupt process termination can leave temporary files, so a real service needs abandoned-job cleanup. This exercise deletes the source copy. A product that needs to regenerate derivatives must separately define private original storage and retention.

Checks must include rejection

15 tests with 108 assertions ran on PHP 8.5.12 with GD/EXIF, including the real Console command through the Kernel and its configured child worker. They cover refusals, all 8 EXIF orientations, transparency, metadata removal, and the absence of a partial accepted directory after failure or timeout. This establishes neither an OS sandbox, a malware verdict, HTTP-upload integration, nor production sizing.

Input or event Expected outcome
PNG with a JPEG extension Decisions use bytes; output format follows policy
Excessive bytes, side, or area Rejection at the relevant boundary
Corrupted data No accepted image
JPEG with a specified orientation Correct dimensions and colored region positions
A PNG comment The original comment is absent from the output
Failure or timeout after a partial write No directory appears in accepted

Add these entries under the existing services block. Decoder explicitly points to PhpDecoder; workerScript points to src/ImageAcceptance/worker.php, and storageRoot to var/image-acceptance in the same application. Preserve existing configuration and keep storage outside public.

services:
    App\ImageAcceptance\Ingestor:
        arguments:
            $storageRoot: '%kernel.project_dir%/var/image-acceptance'
    App\ImageAcceptance\PhpDecoder:
        arguments:
            $workerScript: '%kernel.project_dir%/src/ImageAcceptance/worker.php'
    App\ImageAcceptance\Decoder:
        alias: App\ImageAcceptance\PhpDecoder
    App\Command\AcceptImageCommand: ~

For your own synthetic local PNG/JPEG fixture, from the article_demo root:

php bin/console app:image:accept /absolute/path/to/synthetic-image.png

Do not use working photographs containing personal data. The file must already exist. Quarantine and accepted directories must be private and unavailable to unrelated writers.

After this acceptance stage, the media model receives a specific normalized file and its provenance. Upload authorization, user quotas, public delivery, antivirus scanning, content moderation, and crash recovery remain separate tasks. An acceptance boundary becomes useful when its checked properties and the limits of its guarantees are clear.

  1. Article Engineering An image as a separate asset: identity, originals, and derivatives
  2. Editorial Editorial HTML as data: safe storage and predictable presentation
  3. Article Engineering One cover for different screens: cropping and responsive delivery