Skip to content

Chapter 32 of 38

File Uploads and Image Handling

Validate transport, MIME, size, names, storage, decoding, and image output.

44 minutes 10 quick checksBy Subha Prasad
Lesson 32 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Uploaded metadata and filenames are untrusted. Check transport error and size, then inspect content through finfo or actual decoding rather than extension or client MIME.

Practical example

<?php
$file = $_FILES['image'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK || $file['size'] > Limits::MAX_UPLOAD_BYTES) throw new RuntimeException();
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
if (!in_array($mime, ['image/jpeg', 'image/png'], true)) throw new RuntimeException();

Generate server-side names, store outside executable/public paths, and use move_uploaded_file. Decode/re-encode images with resource limits, remove metadata where policy requires, scan risky formats, and serve with fixed content type plus safe download headers.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes $_FILES?
Which PHP term matches this description: Metadata for HTTP file-upload fields.
Which statement best describes UPLOAD_ERR_OK?
Which PHP term matches this description: The status indicating a successful PHP upload transfer.
Which statement best describes move_uploaded_file?
Which PHP term matches this description: A function moving a verified HTTP upload to controlled storage.
Which statement best describes finfo?
Which PHP term matches this description: Content-based MIME type inspection.
Which statement best describes image re-encoding?
Which PHP term matches this description: Decoding and writing an image to normalize data and remove embedded payloads.

0 of 10 checks passed

Your progress is saved on this device.

File Uploads and Image Handling | PHP Lesson | Subha Prasad