MaggsWeb:7

www.maggsweb.com

PHP Image UpLoader

October 18, 2007 | Comments | PHP

My image upload script. Loads of checks, not all used each time. Optional file-physical-size checks rely on ‘getimagesize’ working. Its long, but stick with it. It works.

<?php
if ((isset($_FILES["txtImage"])) &&
	  ($_FILES["txtImage"]["tmp_name"] != "")) {
  if ($_FILES["txtImage"]["size"] != 0) {
    $imageTypes = array('image/pjpeg'=>'jpg',
			'image/jpeg'=>'jpg',
			'image/gif'=>'gif',
			'image/bmp'=>'bmp',
			'image/png'=>'png');
    if (isset($imageTypes[$_FILES["txtImage"]["type"]])) {
      if ($_FILES['txtImage']['size'] < 500000) {
         //Additional checks for file-physical-size
         //$logo = getimagesize($_FILES["txtImage"]["tmp_name"]);
         //$maximum = 400;
         //if (($logo[0])>$maximum) {
	 //  $error_image = "ERROR: ".$maximum."px Width exceeded";
	 //}
         //if (($logo[1])>$maximum) {
	 //  $error_image = "ERROR: ".$maximum."px Height exceeded";
	 //}
	## FILE OK
	$disallowed = array(" ",",","@","!","\"","/","\\","£","$","and so on");
	$fileName = str_replace($disallowed,"_",$_FILES['txtImage']['name']);
	$directory = "image_uploads/";
	//if(!is_dir($directory)) mkdir($directory,0777);
	$destination = $directory.$fileName;
	if (!file_exists($destination)) {
 
	# MOVE FILE

	  if (copy($_FILES['txtImage']['tmp_name'], $destination)) {
	  ##################
	  ###  SUCCESS  ####
	  ##################

	  } else { $errors = true;
		   $error_image = "ERROR: Cannot save Image";}
	} else { $errors = true;
	      	 $error_image = "ERROR: Image already exists";}
      } else { $errors = true;
	       $error_image = "ERROR: File Size exceeds maximum"; }
    } else { $errors = true;
	     $error_image = "ERROR: Image Type not allowed";}
  } else { $errors = true;
	   $error_image = "ERROR: No Image Filesize";}
} else { $errors = true;
	 $error_image = "ERROR: Image Upload Failed"; }
?>
Share this:
  • Print
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • LinkedIn
  • Twitter

Write a Comment

Let me know what you think?