File extension validation on upload will harmful for server

0.64K views
no comments
5 Jul 2015 11:12 pm

Please do not validate file extension on uploading file from user

$_FILE['file_name'];
$ext = pathinfo($_FILE['file_name'],PATHINFO_EXTENSION);
$allow_ext=array('jpg','jpeg','png','gif');
if(in_array($ext,$allow_ext)){
//DO UPLOAD CODE
}

Hackers are created a fake jpg image with no preview and they add code encode on base64 or  gzinflate on picture source when you will open that image on notepad editor you will see code like

eval(gzinflate('HERE ENCODED CODE'))

if you just validate it on extension that file will be uploaded on your server and hackers will easily get your mysql information, server information, php information, send bulk mails create php file manager files on your server, execute shell commands, or whatever they want written in code and they execute with php eval function, in this DDcode site you will find many examples of that codes with decoded.

To prevent from image file hacker attack

Please  use imagesize function, it will return empty array on fake image, validate with mime_type of image instead extension.

example

$file=$_FILE['file_name'];
$imagesize = getimagesize($file);
$imagesize = array_filter($imagesize);
if(is_array($imagesize) && !empty($imagesize)){
	$image_mime = $imagesize['mime'];
	if(is_numeric(strpos($mime_text,'image/'))){
		//DO UPLOAD CODE
	} else {
		//NOT IMAGE
	}
} else {
	//INVALID IMAGE
}

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>