$maxBytes) { throw new InvalidImageException("File exceeds the {$maxBytes} byte limit."); } $handle = fopen($tempPath, 'rb'); if ($handle === false) { throw new InvalidImageException('Could not read upload.'); } $header = fread($handle, 12); fclose($handle); if ($header === false || strlen($header) < 12) { throw new InvalidImageException('Upload is too small to be an image.'); } $detected = self::detect($header); if ($detected === null) { throw new InvalidImageException('File is not a supported image type.'); } [$canonical, $extension] = $detected; if ($declaredMime !== $canonical) { throw new InvalidImageException('Declared MIME does not match file contents.'); } $info = getimagesize($tempPath); if ($info === false) { throw new InvalidImageException('Image is corrupt or unreadable.'); } [$width, $height] = $info; if ($width > $maxDimension || $height > $maxDimension) { throw new InvalidImageException("Image dimensions exceed the {$maxDimension} pixel limit."); } return new ValidatedImage($canonical, $extension); } }