I haven't tested this code but you could try something like this... It checks for MIME types, which is better than your current method. Might make sense to rename it something like uploadFile
rather than uploadImage
as well. And the $width
variable no longer makes sense for non-image files.
function uploadImage($tmp, $name, $width, $folder) {
// initialize variables
$img = $ext = null;
// supported file types
$valid_mimes = array('pdf' => 'application/pdf',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$finfo = new finfo(FILEINFO_MIME_TYPE);
if ($ext = array_search($finfo->file($tmp), $valid_mimes, true)) {
switch($ext) {
case 'pdf': move_uploaded_file($tmp, $folder.$name); break;
case 'jpg': $img = imagecreatefromjpeg($tmp); break;
case 'png': $img = imagecreatefrompng($tmp); break;
case 'gif': $img = imagecreatefromgif($tmp); break;
}
if (isset($img)) {
$x = imagesx($img);
$y = imagesy($img);
$height = ($width*$y) / $x;
$new_img = imagecreatetruecolor($width, $height);
imagealphablending($new_img,false);
imagesavealpha($new_img,true);
imagecopyresampled($new_img, $img, 0, 0, 0, 0, $width, $height, $x, $y);
switch($ext) {
case 'jpg': imagejpeg($new_img, $folder.$name, 100); break;
case 'png': imagepng($new_img, $folder.$name); break;
case 'gif': imagegif($new_img, $folder.$name); break;
}
imagedestroy($img);
imagedestroy($new_img);
}
}
}