Last active
February 16, 2016 05:02
-
-
Save eberfreitas/4e23d2199cce738c57f6 to your computer and use it in GitHub Desktop.
A simple function to performe safe image upload using PHP, with proper mime check and image strip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function save_image_upload($file, $path, $id = null) { | |
$mime2ext = [ | |
'image/jpeg' => 'jpg', | |
'image/jpg' => 'jpg', | |
'image/png' => 'png' | |
]; | |
$ext2functions = [ | |
'jpg' => [ | |
'create' => 'imagecreatefromjpeg', | |
'save' => 'imagejpeg' | |
], | |
'png' => [ | |
'create' => 'imagecreatefrompng', | |
'save' => 'imagepng' | |
] | |
]; | |
$id = is_null($id) ? md5(uniqid(rand(), true)) : $id; | |
$finfo = new finfo(FILEINFO_MIME); | |
$info = $finfo->file($file); | |
$mime = explode(';', $info)[0]; | |
$mimes = array_keys($mime2ext); | |
if (!in_array($mime, $mimes)) { | |
return false; | |
} | |
$ext = $mime2ext[$mime]; | |
$filename = $id . '.' . $ext; | |
$resource = call_user_func($ext2functions[$ext]['create'], $file); | |
if (!$resource) { | |
return false; | |
} | |
$quality = $ext === 'jpg' ? 100 : 0; | |
$result = call_user_func($ext2functions[$ext]['save'], $resource, $path . DS . $filename, $quality); | |
imagedestroy($resource); | |
if ($result) { | |
return $filename; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment