Uploading images problem (Code)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikebr
Forum Contributor
Posts: 243
Joined: Sat Sep 28, 2002 7:05 am

Uploading images problem (Code)

Post by mikebr »

I have found some code to upload images to a folder on my server from my web site, on trying it I find that when pressing the "Submit" button the window reloads, the upload field is blank and there is no image in the "uploads" folder in my "site" folder nor do I get an alert or error of any type, maybe someone could look at the code and tell me where the problem might be?

I am using a Mac with OS10.2.3 and I have the permissions set to read and write for owner, guests and others, I am testing locally.

Also I see on the list of file extensions for image types that the extension .jpg is not included, should this not be an image type accepted for jpeg images as well as .jpeg and .pjpeg?

There are two files with code, the first is the page the upload button and field are on and the second is the code called on pressing "Submit".

The upload page with the foillowing code:

Code: Select all

<?php
<?php
 require_once("./cgi-local/uploadfile.class.php");
 //Delete the comments below or you will get parse errors
 
 $up = new UploadImage($nameofimagefield, // name of your file field with $
    102400, // max file size in bytes
    480,    // max file height
    650,    // max file width
    "uploader", // name of your file field
    "uploads", // path to upload directory 
   $rename_file=true); // default is true set to false 
   // if you don't want the file renamed

 if ($submit) {
   if($up->ValidateUpload()) {
      $up->CopyFile();
    }
 }
    $up->PrintForm(102400); // max file size for html form same as above 
?>
?>
The file "uploadfile.class.php" code:

Code: Select all

<?php
<?php 

 /*============================================== 
 Random name function needed to provide a name for 
 any files that are renamed 
 =================================================*/ 

function RandomFile($pass_len=12) { 

 $allchar = "abcdefghijklmnopqrstuvwxyz" ;
 $str = "";
 mt_srand(( double) microtime()*1000000);
 for($i=0;$i<$pass_len;$i++)
 $str.=substr($allchar,mt_rand(0,25), 1);
 return $str; 

}

 /*================= 
 Start of our class 
 =================== */ 

 class UploadImage{ 

  var $image;
  var $imagesize;
  var $max_file_size;
  var $max_file_height;
  var $max_file_width;
  var $allowed;
  var $rename_file;
  var $path;

 /*============================================ 
 Construtor-This will run when our class is sub 
 ===============================================*/ 

 function UploadImage($image,
  $max_file_size,
  $max_file_height,
  $max_file_width,
  $field_name,
  $path,
  $rename_file=true) {


  $this->image=$image;
  $this->max_file_size=$max_file_size;
  $this->max_file_height=$max_file_height;
  $this->max_file_width=$max_file_width;
  $this->allowed = array(".gif"=>"1",
          ".jpg"=>"2",
          ".jpeg"=>"2",
          ".png"=>"3",
          ".psd"=>"4",
          ".bmp"=>"5",
         //".swf"=>"6",
         );
   $this->field_name = $field_name;
   $this->path = $path;
   $this->rename_file = $rename_file;
   } 

 /*================================================ 
  Validate the form- This method will validate 
  the form and print out an error message if needed 
  =================================================*/ 

 function ValidateUpload() {

 /*========================================
  Get the size in kb of the file and
  prints an error is it exceed max_file_size
  ==========================================*/

 if ($this->max_file_size < filesize($this->image)) {

  print("<span style="color:red;">ERROR: Your File: "
  .$_FILES[$this->field_name]["name"]." is ".filesize($this->image).
  " KB, the max file size allowed is "
  .$this->max_file_size."</span>");

  return false;

  }

 /*===============================================
  gets the width of the file and prints an error if
  file width is greater than max_file_width
  =================================================*/

 $this->imagesize=getimagesize($this->image);

 if ($this->max_file_width < $this->imagesize[0]) {

  print("<span style="color:red;">ERROR:<br />Your File: "
  .$_FILES[$this->field_name]["name"]." is ".$this->imagesize[0].
  " pixels wide, the max file width allowed is "
  .$this->max_file_width."</span>");

  return false;

  } 

 /*=============================================== 
  gets the height of the file and prints an error if
  file height is greater than max_file_width
  =================================================*/

 if($this->max_file_height < $this->imagesize[1]) {

  print("<span style="color:red;">ERROR:<br />Your File: "
   .$_FILES[$this->field_name]["name"]." is ".$this->imagesize[1].
   " pixels high, the max file height allowed is "
   .$this->max_file_height."<span>");

   return false;

   }

 /*===============================================
  gets the filetype and checks it against
  allow types and returns an error if not in array 
  =================================================*/

 if(!in_array($this->imagesize[2], $this->allowed)) {

  print("<span style="color:red;">ERROR:<br />Your File: "
  .$_FILES[$this->field_name]["name"]." is not included
  in the list of allowed filetype</span>"
  );

  return false;

  }

 /*==================================
  COOL:- no errors so lets get the file
  ====================================*/

  return true;
  }

 /*============================================
  This method will print the form out on our page
  ==============================================*/

 function PrintForm($max_file_size) {

  global $PHP_SELF;

  print("<form action="$PHP_SELF" method="post" enctype="multipart/form-data"></br>\n");
  print("<input type=file name=$this->field_name><br>\n");
  print("<input type=hidden name=max_file_size value=".$max_file_size."><br>\n");
  print("<input type=submit name=submit><br>\n");
  print("</form>");

} 

 /*=============================================
  This method will copy our file to the folder of
  your choice and rename it if selected rename it
  ================================================*/
  
 function CopyFile() {
  if($this->rename_file) {

 /*====================================
  this will find out our file extension which
  we need for renaming it.
  ========================================*/

 switch($_FILES[$this->field_name]["type"]) {

  case 'image/gif';
  $ext="gif";
  break;

  case 'image/jpeg';
  $ext="jpg";
  break;
  
  case 'image/pjpeg';
  $ext="jpg";
  break;

  case 'image/png';
  $ext="png";
  break;

  //case 'application/x-shockwave-flash';
  //$ext="swf";
  //break;

  case 'image/psd';
  $ext="psd";
  break;

  case 'image/bmp';
  $ext="bmp";
  break;
}

 /*========================================================
  Let's rename our file and then copy it to the directory
  =========================================================*/

 $name=RandomFile();

 if(!@copy($_FILES[$this->field_name]["tmp_name"],$this->path."/".$name.".".$ext)) {
 print("<b>There has been an error while uploading Filename: ".$_FILES[$this->field_name]["name"] ." </b>");

 } else {

 print("Filename: ".$_FILES[$this->field_name]["name"] ." has been uploaded");

}

} else {

 /*===================================================
  if you don't want the file renamed then this will run
  let's make sure the file doesn't exist already and if
  it does let's return an error
 =====================================================*/

 if(!file_exists($this->path."/".$_FILES[$this->field_name]["name"])) {

  if(!@copy($_FILES[$this->field_name]["tmp_name"],$this->path."/". $_FILES[$this->field_name]["name"])) {

  print("There has been an error uploading ".$_FILES[$this->field_name]["name"]." please try again");

  } else {

   print("Filename: ".$_FILES[$this->field_name]["name"]." has been uploaded");

  }
   } else {

   print("ERROR: A file by this name already exists");

    }

   }

  }

 }

?>
?>
mikebr
Forum Contributor
Posts: 243
Joined: Sat Sep 28, 2002 7:05 am

Post by mikebr »

OK, if no one can or has the time to see where the problem is in the code which I do understand as it's not a quick example, then maybe someone can point me to where they know of some other sample code that works with PHP 4.2 that will upload images to a server?. I am at a dead end here as I have looked at various samples from the php manual, php websites and from a couple of books I have but none of them seem to do anything, no errors, just reload the form so I guess they are possibly all out of date with where php is now and hell if I can find out the changes needed to get them to work. I am testing on my laptop with Jaguar 10.2.3 but as I understand it this shouldn't make any difference to the php?

Thanks
mikebr
Forum Contributor
Posts: 243
Joined: Sat Sep 28, 2002 7:05 am

Post by mikebr »

I wrote some simpler code to upload the files myself and have found that the variables for $userfile is not getting passed on (I should have checked this before as that will be the problem in the first code I posted) anyway after looking I can't seem to find out why, I have used POST to get the content of MAX_FILE_SIZE but the variable for "$filetype" still seems to be empty, if anyone can see why $userfile is not getting passed on or what the problem is would they mind telling me please?

The Upload field:

Code: Select all

&lt;FORM ENCTYPE="MULTIPART/FORM-DATA" ACTION="cgi-local/upload.php" METHOD="POST"&gt;
&lt;INPUT TYPE="HIDDEN" NAME="MAX_FILE_SIZE" VALUE="102400"&gt;
&lt;INPUT NAME="userfile" TYPE="file"&gt;
&lt;INPUT TYPE="submit" NAME="submit" VALUE="SEND FILE"&gt;
&lt;/form&gt;
The upload.php file:

Code: Select all

<?php
<?php

$MAX_FILE_SIZE = $_POST['MAX_FILE_SIZE'];
$userfile = $_POST['userfile'];

if($userfile=="none") {
	echo "Problem: No file uploaded";
	exit;
}

if($userfile_size=="0") {
	echo "Problem: Uploaded file is zero in length";
	exit;
}

switch ($userfile_type) {

	case "image/gif":
	$ext = ".gif";
	break;
	
	case "image/jpeg":
	$ext = ".jpg";
	break;
	
	case "image/pjpeg":
	$ext = ".jpg";
	break;
	
	default:
	 $error = "Problem: Uploaded file is not right file type";
	break;
	}
	
if(isset($error)) {
 echo "$error";
 exit;
}

if(!$is_uploaded_file($userfile)) {
	echo "Problem: Possible file upload attack";
	exit;
}

$upfile = "./uploads/".$userfile_name;

if(!copy($userfile.$upfile))
{
	echo "Problem: Could not copy file to directory";
	exit;
}

echo "File uploaded successfully<br></br>";
?>
:cry:
Post Reply