How well does this code limit security problems when uploading images to the server?
<?php
$filename = $_FILE['inputfile']['name'];
$upload_path = 'images/';
//extract extension
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//get MIME type of the given file
$mime = finfo_file($finfo, $filename);
//close finfo
finfo_close($finfo);
if (is_uploaded_file($_FILES['inputfile']['tmp_name'])) {
//first check: file extension and mime type
if(!in_array($ext, array('jpeg', 'jpg', 'gif', 'png')) && !in_array($mime, array('image/jpeg', 'image/gif', 'image/png')) ){
die("Error1: Invalid Image type");
}
//create image according to MIME type
//first: JPEG and JPG
if($ext == 'jpeg' || $ext == 'jpg'){
//move_uploaded_file ignored because no need to use it
$im = @imagecreatefromjpeg($_FILE['inputfile']['tmp_name']);
if($im){
$createimage = imagejpeg($im, $upload_path.$_FILE['inputfile']['name']);
if(!$createimage){
die("Error3: Can't create image!");
}
//last check
$filecontent = file_get_contents($upload_path.$_FILE['inputfile']['name']);
//clean the file from any php code
//changed
while(preg_match('#<\?php|\?>|<\?#i', $filecontent)){
$filecontent = str_replace(array("<?php", "<?", "?>"), "", $filecontent);
}
$handle = fopen($upload_path.$_FILE['inputfile']['name'], "wb");
fwrite($handle, $filecontent);
fclose($handle);
}
else{
die("Error2: Invalid Image Detected");
}
}
}
?>
Edit:
while(preg_match('#<\?php|\?>|<\?#i', $filecontent)){
$filecontent = str_replace(array("<?php", "<?", "?>"), "", $filecontent);
}