Checking an uploaded file

The upload handler of form2 (form/upload) checks every file it stores: the name (one allowed extension, no denied part such as a.php.jpg), the size, a PHP open tag in the first 64 KB, the type fileinfo reads, and it re-encodes images with GD. check_file() runs the same checks on a file that did not come through the upload widget: a plain $_FILES upload of a plugin, a file a job fetched, a direct upload to a bucket downloaded for a check.

$fh = _class('form2_file_handler', 'classes/form2/');
$ext = strtolower(pathinfo((string) $_FILES['photo']['name'], PATHINFO_EXTENSION));   // check_file() refuses it unless allowed
$r = $fh->check_file($_FILES['photo']['tmp_name'], $_FILES['photo']['name'], [
    'uploaded' => true,                       // the path must be an upload of this request (default false)
    'dest' => $dir . bin2hex(random_bytes(16)) . '.' . $ext,   // where to write the checked file: same extension
    'extensions' => ['jpg', 'jpeg', 'png', 'webp'],        // narrower than ALLOWED_EXTENSIONS
    'max_size' => 5 * 1048576,
]);
if ( ! $r['ok']) { return $r['error']; }   // 'file type not allowed', 'file content not allowed', 'invalid image', ...
// $r: ['ok' => true, 'error' => null, 'ext' => 'jpg', 'path' => the checked file, 'size' => bytes]
  • Without dest the file stays where it is: an image is re-encoded in place (through a temporary file in the same folder), any other file is only checked.
  • With dest the checked file is written there (re-encoded, copied, or moved for an uploaded file) with mode 0644; the source is left alone. The extension of dest must be the one that was checked (any case), else the file is refused (the destination extension does not match the file): a checked a.jpg written as x.php would run on the server.
  • uploaded is false by default: the path is then any file the caller trusts to name (a job's download). For a $_FILES upload always pass 'uploaded' => true, so a forged tmp_name such as /etc/passwd is refused (is_uploaded_file()); an upload needs dest.
  • Options: max_size (bytes, default MAX_FILE_SIZE, 0 no limit), reencode (default REENCODE_IMAGES), extensions. DENIED_EXTENSIONS always win.
  • A link (symlink), a missing or empty file is refused; on a refusal nothing is left at dest. The event media.stored is not fired: the caller decides what a stored file is.

Legacy image helpers: metadata is always dropped

common()->upload_image(), common()->multi_upload_image(), common()->make_thumb() (GD and Imagick) and the rich text editor uploads re-encode every image they store (yf 3.x, M6a: a privacy fix with no flag). Only the pixels are kept: EXIF (with the GPS position of a phone photo), XMP, comments, ICC profiles and any bytes appended after the image (a polyglot with PHP code) are gone, and a byte-identical copy of the upload is no longer kept. Their signatures did not change.

  • Type from the bytes. The client MIME ($_FILES[...]['type']) is ignored: getimagesize() and, when the fileinfo extension is loaded, finfo must agree on jpeg, png, gif, webp or avif (for upload_image() also one of its ALLOWED_MIME_TYPES). A real JPEG sent as application/octet-stream is accepted; a text file sent as image/jpeg is refused.
  • Pixel limit before decoding. Width x height from the image header must not exceed MAX_PIXELS (40 Mpx by default), so a 1 KB PNG that claims 50 000 x 50 000 pixels is refused (Image dimensions are too large) before GD or Imagick try to allocate it. make_thumb() refuses such a source too (returns false with a warning).
  • Orientation. The EXIF orientation of a JPEG is applied before the metadata is dropped, so phone photos are stored upright (the GD path needs the exif extension; without it the image keeps the stored orientation).
  • GIF. An animated GIF keeps its first frame only (GD reads one frame; the Imagick path takes the first one too).
  • make_thumb() with GD re-encodes even when no resize is needed (it used to copy the source bytes, metadata included). With Imagick the input coder is named from the sniffed type, never guessed from the content (so MVG, MSL, SVG, PS or PDF are not decoded whatever ImageMagick's policy.xml allows), resource limits are set for the read and the previous ones restored right after it (they are process-wide in a PHP-FPM worker), and other types (bmp, tiff...) are refused.
  • Without GD (or Imagick) support for the type the image is refused: it cannot be cleaned. Non-image files of the rich text editor (pdf, office, zip, media) and bmp / ico images are stored as before.

The same steps are available to plugin code as _class('image_clean', 'classes/common/'):

$ic = _class('image_clean', 'classes/common/');
$info = $ic->sniff($path, ['jpeg', 'png']);   // ['type' => 'jpeg', 'mime', 'width', 'height'] or 'invalid image' / 'image type not allowed' / 'image is too large'
$r = $ic->clean($path);                        // in place; clean($src, $dest) writes $dest and leaves $src alone
if ( ! $r['ok']) { return $r['error']; }      // $r: ['ok', 'error', 'type', 'width', 'height'] (sizes after orientation)

Settings ($PROJECT_CONF['image_clean']): MAX_PIXELS (40000000, 0 no limit), JPEG_QUALITY (90), WEBP_QUALITY (90, also AVIF), TYPES (sniffed MIME => type), IMAGICK_LIMITS (memory 256 MB, map 512 MB, disk 1 GB, area 128 Mpx, width and height 32768). A time key is ignored: ImageMagick 6 counts that limit from the worker's first decode, so once a long-lived PHP-FPM worker is older than it, every later Imagick call in that worker would fail, other code included.