The code below is modified from an O’Reilly Book – Learning PHP, MySQL, and JavaScript which can be found here
Why are all image types converted to .jpg?
Does .jpg offer the best quality/size ratio?
public static function upload()
{
$email=$_SESSION['email'];
$path1="i8.jpg";
$path2="z_p/$email.jpg";
$path3="i9.jpg";
$path4="z_p/$email-1.jpg";
if(move_uploaded_file($_FILES['ufile']['tmp_name'], $path2))
{
$typeok=TRUE;
switch($_FILES['ufile']['type'])
{
case "image/gif":
$src = imagecreatefromgif($path2);
break;
case "image/jpeg":
case "image/pjpeg":
$src = imagecreatefromjpeg($path2);
break;
case "image/png":
$src = imagecreatefrompng($path2);
break;
default:
$typeok = FALSE;
break;
}
if($typeok)
{
list($w, $h) = getimagesize($path2);
$tw = $w;
$th = $h;
/*Run 1*/
$max = 50;
if($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$dst = imagecreatetruecolor($tw, $th);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imagejpeg($dst, $path2);
imagedestroy($dst);
/* Rune 2 */
$max = 20;
if($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$dst = imagecreatetruecolor($tw, $th);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imagejpeg($dst, $path4);
imagedestroy($dst);
imagedestroy($src);
}
}
else
{
copy($path1, $path2);
copy($path3, $path4);
}
}
There are lots of nasty surprises you can hide inside a jpeg file (or any of a number of image formats). By always recreating an image this way, you gain a certain amount of confidence that the image your server issues is sanitized.