Jump to content

Help Improving Image Upload Script please


portalpie

Recommended Posts

Hello,

 

My upload script is working for the most part and while I know that I need a couple of little fixes and will need help with those I also wouldn't mind some tips on how I could have written it better in the first place.

 

The 2 problems I am having.

1. If the copy image fails the script doesn't and still creates a database entry. I would like to stop it from doing that but can't seem to work it out.

2. My mate is getting file type errors even though he is trying to upload small .jpg files. I can't seem to recreate the problem. Maybe someone can see something that might be problematic??

<?
        $idir = "../rosysartworks/gallery/";   // Path To Images Directory
        $tdir = "../rosysartworks/gallery/thumbs/";   // Path To Thumbnails Directory
        $iwidth = "600";   // Maximum Width For Thumbnail Images
        $iheight = "600";   // Maximum Height For Thumbnail Images
        $twidth = "233";   // Maximum Width For Thumbnail Images
        $theight = "178";   // Maximum Height For Thumbnail Images
        ?>

          <? 
        // Catching the inputs
			$title = Trim(stripslashes($_POST['title']));
			$paypal = Trim(stripslashes($_POST['paypal']));
        // Check if the form has been submitted.
			if (isset ($_POST['submit'])) {
				$problems = FALSE; // No problems so far.

				// Check for each value.
				if (empty ($title)) {
					$problem = TRUE;
					$problems = 'You forgot to enter a title!<br />';
				}
				if (empty ($paypal)) {
					$problem = TRUE;
					$problems = 'You forgot to enter a paypal link!<br />';
				}
				if (!$problem) { // If there are no problems...
        
        // Uploading/Resizing Script
        $url = $_FILES['imagefile']['name'];   // Set $url To Equal The Filename For Later Use
        if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/JPG") {
          $file_ext = strrchr($_FILES['imagefile']['name'], '.');   // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
          $copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']);   // Move Image From Temporary Location To Permanent Location
          
          
          if ($copy) {   // If The Script Was Able To Copy The Image To It's Permanent Location
          
            // Resize for preview image.
            $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From
            $currwidth = imagesx($simg);   // Current Image Width
            $currheight = imagesy($simg);   // Current Image Height
            
            if ($currwidth > $iwidth && $currheight > $iheight) {
              $newwidth = $iwidth; 
              $newheight = $newwidth * $currheight / $currwidth; 
              if ($newheight > $iheight) { 
                $newheight = $iheight;
                $newwidth = $newheight * $currwidth / $currheight; }

              $dimg = imagecreatetruecolor($newwidth, $newheight);   // Make New Image For Preview
              imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete
              $palsize = ImageColorsTotal($simg);
              for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image
              $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used
              ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use
              }
              imagecopyresampled($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It)
              $success = imagejpeg($dimg, "$idir" . $url, 100);   // Saving The Image
              imagedestroy($simg);   // Destroying The Temporary Image
              imagedestroy($dimg);   // Destroying The Other Temporary Image

              if ($success) {
                print 'Preview image '.$url.' width: '.$newwidth.' height: '.$newheight.' created successfully.<br />';   // Resize successful for preview image
                unset($success);
              } 
            } else {
              unset($simg, $currwidth, $currheight);
          }
            
            
              // Resize for thumbnail
              $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From
              $currwidth = imagesx($simg);   // Current Image Width
              $currheight = imagesy($simg);   // Current Image Height
            
              $newwidth = $twidth; 
              $newheight = $newwidth * $currheight / $currwidth; 
              if ($newheight > $theight) { 
                $newheight = $theight;
                $newwidth = $newheight * $currwidth / $currheight; }
            
              // maxWidth: mw, maxHeight: mh, oldHeight: oh, oldWidth: ow, newHeight: nh, newWidth: nw.   
              // nw = mw; nh = nw * oh / ow; 
              // if (nh > mh) { nh = mh; nw = nh * ow / oh }
          
              $dimg = imagecreatetruecolor($newwidth, $newheight);   // Make New Image For Thumbnail
              imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete
              $palsize = ImageColorsTotal($simg);
              for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image
              $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used
              ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use
              }
              imagecopyresampled($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It)
              $success = imagejpeg($dimg, "$tdir" . $url, 100);   // Saving The Image
              imagedestroy($simg);   // Destroying The Temporary Image
              imagedestroy($dimg);   // Destroying The Other Temporary Image
              
              if ($success) {
              print 'Image thumbnail '.$url.' width: '.$newwidth.' height: '.$newheight.' created successfully.';   // Thumbnail created successfully
              }
            } else {
            print '<font color="#FF0000">ERROR: Unable to upload image.</font>';   // Error Message If Upload Failed
            } // End upload at copy failure
                 }  else {
                     print 'Failed to copy image to temp location.';
                   }
        } else {
          print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is ';   // Error Message If Filetype Is Wrong
          print $file_ext;   // Show The Invalid File's Extention
          print '.</font>';
        } // End upload script

       
			// Define the query.
  			$add_new_session = $sql = "INSERT INTO  `gallery` (
  			`id` ,
  			`title` ,
  			`image` ,
  			`thumb` ,
  			`width` ,
  			`height` ,
  			`paypal` ,
  			`date_entered`
  			)
  			VALUES (
  			0,
  			'".mysql_real_escape_string(($title))."', 
  			'".mysql_real_escape_string(($url))."', 
  			'".mysql_real_escape_string(($url))."', 
  			'".mysql_real_escape_string(($newwidth))."', 
  			'".mysql_real_escape_string(($newheight))."',
  			'".mysql_real_escape_string(($paypal))."',
  			NOW()
  			)";

  				// execute the query.
  				if (@mysql_query ($add_new_session)) {
  					print "<p>The new gallery image $url has been added.</p>";
  					unset($sessionName, $maxAttendees, $newwidth, $newheight);
  					$hidden = 'hidden';
			}
			else{
			  	print '<a name="formTop"></a>'.'<p class="error">Your session has failed to upload. Please contact website support.</p>';
			  	echo $add_new_session;
			}
			} else { // Forgot a field.

			//	print '<p>Please try again!</p>';
				$problems .= '<a name="formTop"></a>'.'Please try again!<br />';
				if ($problem) {
					print '<p class="error">' . $problems . '</p>';
				}
			}

	 // End of handle form IF
		// Display the form

	print '<h2>Upload New Image</h2>'
	. '<p>Please only try uploading .jpg images</p>'
	  . '<form method="post" action="index.php" enctype="multipart/form-data">'
	  . '<label>Title:</label>'
      . '<input type="text" name="title" class="form">'
      . '<br />'
      . '<label>Image:</label>'
      . '<input type="file" name="imagefile" class="form">'
      . '<br />'
      . '<label>Paypal Link:</label>'
      . '<input type="text" name="paypal" class="form" size="50">'
      . '<br /><br />'
      
      . '<input name="submit" type="submit" value="Sumbit" class="form">'
      . '<input type="reset" value="Clear" class="form">'
	  . '</form>';
?> 

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.