Hi
i am new php programmer, and i need your help please

i have a page that allows for public visitors to upload multi images
but some hackers using my page to upload php files by using image forms to hack my website.

i tried to add some code in my page to limit extension (to just upload images and protect to upload php files)

but now working.....

<?php

if(isset($_POST['submit']))
	{
		
			
		//make sure this directory is writable!
		$path_thumbs = "Cars/thumb/";
		$path_big = "Cars/pictures/";
		
		//the new width of the resized image, in pixels.
		$img_thumb_width = 150; // 

		$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
		//List of allowed extensions if extlimit = yes
		$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp","");
		
		//the image -> variables
	    $file_type = $_FILES['vImage']['type'];
        $file_name = $_FILES['vImage']['name'];
        $file_size = $_FILES['vImage']['size'];
        $file_tmp = $_FILES['vImage']['tmp_name'];

        $file_name2 = $_FILES['car_pic2']['name'];
	    $file_tmp2 = $_FILES['car_pic2']['tmp_name'];
		
        $file_name3 = $_FILES['car_pic3']['name'];
		$file_tmp3 = $_FILES['car_pic3']['tmp_name'];
		
		$file_name4 = $_FILES['car_pic4']['name'];
        $file_tmp4 = $_FILES['car_pic4']['tmp_name'];
        
		$file_name5 = $_FILES['car_pic5']['name'];
		$file_tmp5 = $_FILES['car_pic5']['tmp_name'];


        //check if you have selected a file.
    /*  if(!is_uploaded_file($file_tmp)){
           echo "Error: Please select a file to upload!. <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
           exit(); //exit the script and don't process the rest of it!
        }*/
       //check the file's extension
       $ext = strrchr($file_name,'.');
       $ext = strtolower($ext);
       //uh-oh! the file extension is not allowed!
       if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
          echo "Wrong file extension.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
       }
       //so, whats the file's extension?
       $getExt = explode ('.', $file_name);
       $file_ext = $getExt[count($getExt)-1];


       //create a random file name
       $rand_name = md5(time());
       $rand_name= rand(0,999999999);
	   
	   
       //the new width variable
       $ThumbWidth = $img_thumb_width;

	   //////////////////////////
	   // CREATE THE THUMBNAIL //
	   //////////////////////////
	   
       //keep image type
       if($file_size){
          if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
               $new_img = imagecreatefromjpeg($file_tmp);
           }elseif($file_type == "image/x-png" || $file_type == "image/png"){
               $new_img = imagecreatefrompng($file_tmp);
           }elseif($file_type == "image/gif"){
               $new_img = imagecreatefromgif($file_tmp);
           }
           //list the width and height and keep the height ratio.
           list($width, $height) = getimagesize($file_tmp);
           //calculate the image ratio
           $imgratio=$width/$height;
           if ($imgratio>1){
              $newwidth = $ThumbWidth;
              $newheight = $ThumbWidth/$imgratio;
           }else{
			   $ThumbWidth = 110;
                 $newheight = $ThumbWidth;
                 $newwidth = $ThumbWidth*$imgratio;
           }
           //function for resize image.
           if (function_exists(imagecreatetruecolor)){
           $resized_img = imagecreatetruecolor($newwidth,$newheight);
           }else{
                 die("Error: Please make sure you have GD library ver 2+");
           }
           //the resizing is going on here!
           imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
           //finally, save the image
		   if($file_name != NULL){
		   $thumb = $rand_name.$file_name;
		   }
		   
		   if($file_name2 != NULL){
			  $thumb2 = $rand_name.$file_name2;
			   }
			if($file_name3 != NULL){
			  $thumb3 = $rand_name.$file_name3;
			   }   
			if($file_name4 != NULL){
			  $thumb4 = $rand_name.$file_name4;
			   }   
		   
		   if($file_name5 != NULL){
			  $thumb5 = $rand_name.$file_name5;
			   }
	
		   
           ImageJpeg ($resized_img,"$path_thumbs/$thumb");
           ImageDestroy ($resized_img);
           ImageDestroy ($new_img);
           
           
        }

        //ok copy the finished file to the thumbnail directory
		move_uploaded_file ($file_tmp, "$path_big/$thumb");
		move_uploaded_file ($file_tmp2, "$path_big/$thumb2");
		move_uploaded_file ($file_tmp3, "$path_big/$thumb3");
		move_uploaded_file ($file_tmp4, "$path_big/$thumb4");
		move_uploaded_file ($file_tmp5, "$path_big/$thumb5");
	
}

?>

any help please???

Try this.....i use this in my website. Note: $_SESSION must be set already.

<?php

session_start();

$user=$_SESSION;

$imgname=$_POST;

function findexts1 ($filename)
{
$filename = strtolower($filename) ;
$exts1 = split("[/\\.]", $filename) ;
$n = count($exts1)-1;
$exts1 = $exts1[$n];
return $exts1;
}

$ext1 = findexts1 ($_FILES) ;

$imagename = md5(rand() * time());


$ran = $imagename;

$ran2 = $ran.".";

$target = "uploads/";

$target = $target.$ran2.$ext1;

if(move_uploaded_file($_FILES, $target))
{
echo "The picture has been uploaded";

$con=mysql_connect("localhost","user","password");

$db=mysql_select_db("databasename");

$query=mysql_query("insert into images values('$user','$target','$imgname')");

mysql_close($con);

}
else
{
echo "<font color='#000000' size='3pt'>Sorry, there was a problem uploading your picture</font>";
}

?>

well ... if the user manages to upload a php file with .php file extension despite your checking...then you can run a simple script after each upload to check if the upload directory has any php file in it... if found just delete it with your script...

else you can also open the file contents of the file just uploaded using curl ( preferably ) and check to see the if it has any <?php ?> or javascript or anything like that using regexp...

thanks rajesh1158 and thanks dos_killer

really i am new programmer (beginner)

my code from the web

could anyone please correct my code, as you say dos_killer,

#
//ok copy the finished file to the thumbnail directory
#
move_uploaded_file ($file_tmp, "$path_big/$thumb");
#
move_uploaded_file ($file_tmp2, "$path_big/$thumb2");
#
move_uploaded_file ($file_tmp3, "$path_big/$thumb3");
#
move_uploaded_file ($file_tmp4, "$path_big/$thumb4");
#
move_uploaded_file ($file_tmp5, "$path_big/$thumb5");
#
 
#
}

add script before upload or any another way

Member Avatar for diafol

There's no point trying to stop an upload - forms can be spoofed. Deal with the actual upload - kill it if it isn't a legit. graphics file. I would also rename any file with a ridiculous hashed name so that even in the eventuality of a successful malicious upload, the hacker would not be able to fire up his nefarious script. Keep the file details in a DB (e.g. user_id, title, newfilename (the hashed filename), origfilename etc).

//EDIT

example of hashed name (if $filename is the orig name):

$newfilename = md5("this will rename you young filename" . $filename);

You can make the hash even more silly, but it's probably unnecessary.

Mind you, I came across this site a while back, I assume it's still relevant:

http://www.scanit.be/uploads/php-file-upload.pdf

<?php
	$str='fhfhf<?php echo "hacker"; ?>';
	$pattern='/<\?(.*)\?>/';
	if(preg_match_all($pattern, $str, $matches)) 
	{
		print $matches[1][0];
	}
	else
		echo "Not found";
?>

This should could capture any server sidescripting in the uploaded file..and in case you find anything suspiscious..just delete the file there itself and not let it be uploaded...! also renaming the file to a salted hash is good..
like
$file_name=md5($actual_filename.$super_secret_code);

Dear mapee,

Check the below link for file uploading operations.
http://www.w3schools.com/php/php_file_upload.asp

use the below code to check the file type

print_r($_FILES[file][type]);

if file type specifies it is a php file . Then omit it by using the condition.

Thank you,

Regards,
prem

thank you very much
i will try as you told me and i will tell you

thanks, you are great

Hello All, thank you for all your information,

really it was very useful,

i solved many issues:

1. limit extension jpeg png gif
2. force file without extension
3. rename the file

still one important thing, i found on my server file with extension gif, but it not image, i opened it by textedit and found php codes...

as dos_killer said:

<?php
	$str='fhfhf<?php echo "hacker"; ?>';
	$pattern='/<\?(.*)\?>/';
	if(preg_match_all($pattern, $str, $matches)) 
	{
		print $matches[1][0];
	}
	else
		echo "Not found";
?>

we have to check the file content


really i tried to use the code above, but i failed to use it

dos_killer, or anyone could you please help me how to use it??

this is my new code:

<?php

if(isset($_POST['submit']))
	{
		
		//make sure this directory is writable!
		$path_thumbs = "Cars/thumb/";
		$path_big = "Cars/pictures/";
		
		//the new width of the resized image, in pixels.
		$img_thumb_width = 150; // 

		$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
		//List of allowed extensions if extlimit = yes
		$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp","");
		
		//the image -> variables
	    $file_type = $_FILES['vImage']['type'];
        $file_name = $_FILES['vImage']['name'];
        $file_size = $_FILES['vImage']['size'];
        $file_tmp = $_FILES['vImage']['tmp_name'];

        $file_type2 = $_FILES['car_pic2']['type'];
		$file_name2 = $_FILES['car_pic2']['name'];
	    $file_tmp2 = $_FILES['car_pic2']['tmp_name'];
		
		$file_type3 = $_FILES['car_pic3']['type'];
        $file_name3 = $_FILES['car_pic3']['name'];
		$file_tmp3 = $_FILES['car_pic3']['tmp_name'];
		
		$file_type4 = $_FILES['car_pic4']['type'];
		$file_name4 = $_FILES['car_pic4']['name'];
        $file_tmp4 = $_FILES['car_pic4']['tmp_name'];
        
		$file_type5 = $_FILES['car_pic5']['type'];
		$file_name5 = $_FILES['car_pic5']['name'];
		$file_tmp5 = $_FILES['car_pic5']['tmp_name'];


        //check if you have selected a file.
    /*  if(!is_uploaded_file($file_tmp)){
           echo "Error: Please select a file to upload!. <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
           exit(); //exit the script and don't process the rest of it!
        }*/
       //check the file's extension
       $ext = strrchr($file_name,'.');
       $ext = strtolower($ext);
	   
	   $ext2 = strrchr($file_name2,'.');
       $ext2 = strtolower($ext2);
	   
	   $ext3 = strrchr($file_name3,'.');
       $ext3 = strtolower($ext3);
	   
	   $ext4 = strrchr($file_name4,'.');
       $ext4 = strtolower($ext4);
	   
	   $ext5 = strrchr($file_name5,'.');
       $ext5 = strtolower($ext5);
       //uh-oh! the file extension is not allowed!
       if (($extlimit == "yes") && (!in_array($ext,$limitedext))){
          echo "Wrong file type.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
       }
	  	  
       //so, whats the file's extension?
       $getExt = explode ('.', $file_name);
       $file_ext = $getExt[count($getExt)-1];
	   
	  
	   
	   if (($extlimit == "yes") && (!in_array($ext2,$limitedext))) {
          echo "Wrong file type.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
       }
       //so, whats the file's extension?
       $getExt2 = explode ('.', $file_name2);
       $file_ext2 = $getExt2[count($getExt2)-1];
	   
	   
	   if (($extlimit == "yes") && (!in_array($ext3,$limitedext))) {
          echo "Wrong file type.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
       }
       //so, whats the file's extension?
       $getExt3 = explode ('.', $file_name3);
       $file_ext3 = $getExt3[count($getExt3)-1];
	   
	   
	    if (($extlimit == "yes") && (!in_array($ext4,$limitedext))) {
          echo "Wrong file type.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
       }
       //so, whats the file's extension?
       $getExt4 = explode ('.', $file_name4);
       $file_ext4 = $getExt4[count($getExt4)-1];
	   
	   if (($extlimit == "yes") && (!in_array($ext5,$limitedext))) {
          echo "Wrong file type.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
       }
       //so, whats the file's extension?
       $getExt5 = explode ('.', $file_name5);
       $file_ext5 = $getExt5[count($getExt5)-1];
	   

	  // check if no extension and has name 
	  if (($file_name !="") && ($ext == "")){
	      //echo "no extension.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
	  }
	  
	  	  if (($file_name2 !="") && ($ext2 == "")){
	     // echo "no extension.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
	  }
	  
	  	  if (($file_name3 !="") && ($ext3 == "")){
	     // echo "no extension.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
	  }
	  
	  	  if (($file_name4 !="") && ($ext4 == "")){
	     // echo "no extension.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
	  }
	  
	  	  if (($file_name5 !="") && ($ext5 == "")){
	     // echo "no extension.  <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";
          exit();
	  }
	  


       //create a random file name
       $rand_name = md5(time());
       $rand_name= rand(0,999999999);
	   
	   
       //the new width variable
       $ThumbWidth = $img_thumb_width;

	   //////////////////////////
	   // CREATE THE THUMBNAIL //
	   //////////////////////////
	   
       //keep image type
       if($file_size){
          if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
               $new_img = imagecreatefromjpeg($file_tmp);
           }elseif($file_type == "image/x-png" || $file_type == "image/png"){
               $new_img = imagecreatefrompng($file_tmp);
           }elseif($file_type == "image/gif"){
               $new_img = imagecreatefromgif($file_tmp);
           }
           //list the width and height and keep the height ratio.
           list($width, $height) = getimagesize($file_tmp);
           //calculate the image ratio
           $imgratio=$width/$height;
           if ($imgratio>1){
              $newwidth = $ThumbWidth;
              $newheight = $ThumbWidth/$imgratio;
           }else{
			   $ThumbWidth = 110;
                 $newheight = $ThumbWidth;
                 $newwidth = $ThumbWidth*$imgratio;
           }
           //function for resize image.
           if (function_exists(imagecreatetruecolor)){
           $resized_img = imagecreatetruecolor($newwidth,$newheight);
           }else{
                 die("Error: Please make sure you have GD library ver 2+");
           }
           //the resizing is going on here!
           imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
           //finally, save the image
		   if($file_name != NULL){
		   $thumb = $rand_name.$file_name;
		   }
		   
		   if($file_name2 != NULL){
			  $thumb2 = $rand_name.$file_name2;
			   }
			if($file_name3 != NULL){
			  $thumb3 = $rand_name.$file_name3;
			   }   
			if($file_name4 != NULL){
			  $thumb4 = $rand_name.$file_name4;
			   }   
		   
		   if($file_name5 != NULL){
			  $thumb5 = $rand_name.$file_name5;
			   }
			   
		/*   $thumb3 = $rand_name.$file_name3;
		   $thumb4 = $rand_name.$file_name4;
		   $thumb5 = $rand_name.$file_name5;*/
		   
           ImageJpeg ($resized_img,"$path_thumbs/$thumb");
           ImageDestroy ($resized_img);
           ImageDestroy ($new_img);
           
           
        }

        //ok copy the finished file to the thumbnail directory
		move_uploaded_file ($file_tmp, "$path_big/$thumb");
		move_uploaded_file ($file_tmp2, "$path_big/$thumb2");
		move_uploaded_file ($file_tmp3, "$path_big/$thumb3");
		move_uploaded_file ($file_tmp4, "$path_big/$thumb4");
		move_uploaded_file ($file_tmp5, "$path_big/$thumb5");
		

		
	
}


	

?>

and thank you before

in my code you've to replce $str with the content of the file ...
i would use curl for it..its the best method..
nd besides my method is certain to solve yer issues with php files with image extensions..do give it a shot !

for a simple tutorial on curl...go here...this should answer all yer queries ... http://blog.unitedheroes.net/curl/

thank you dos killer, you are really a great,

i will do it

thanks for all of you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.