Skip to content

Instantly share code, notes, and snippets.

@eberfreitas
Last active February 16, 2016 05:02
Show Gist options
  • Save eberfreitas/4e23d2199cce738c57f6 to your computer and use it in GitHub Desktop.
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
<?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