Skip to content

Instantly share code, notes, and snippets.

@eypsilon
Last active November 19, 2020 02:31
Show Gist options
  • Save eypsilon/b3e372c1cae95fc281794797e311ac6e to your computer and use it in GitHub Desktop.
Save eypsilon/b3e372c1cae95fc281794797e311ac6e to your computer and use it in GitHub Desktop.
Checks whether a given resource is an image by creating an image with the corresponding PHP-Image Functions
<?php
/**
* Checks whether a given resource is an image by creating an temporary
* image with the corresponding PHP-Image Functions. Set a custom Extension
* through the second parameter to disable auto-detection and test any file.
* Enable "fopen wrappers" to check also URLs
*
* @param String $file to check. To check an uploaded file use: $_FILES['tmp_name'][X]
* @param String $ext set file Extension to check any File
* @return Bool
*/
function isImage(String $file, String $extension=null): Bool
{
$useFn = [
'gif' => '\imagecreatefromgif',
'png' => '\imagecreatefrompng',
'webp' => '\imagecreatefromwebp',
'jpg' => '\imagecreatefromjpeg',
'jpeg' => '\imagecreatefromjpeg',
];
return $createFrom = ($useFn[\strtolower($extension ?? \pathinfo($file, \PATHINFO_EXTENSION))] ?? false) AND @$createFrom($file);
}
$img = 'https://upload.wikimedia.org/wikipedia/commons/1/17/Faust_image_19thcentury.jpg';
if (isImage($img)) {
print "<img src="$img" alt="Detected Image, {$img}">";
} else {
print 'File is not an image';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment