Image upload

Hi

Im a newbie to php so bear with me. I have a script that will upload images to an ‘images’ folder(I got it form a book I just bought). This works OK, but I need to add a ref to the image to a mysql database too. Can annyone advise me on this?

My code so far:

[php]<DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://w3.org/TR//xhtml1-transitional.dtd”>

Upload an image .error{ font-weight: bold; color:#c00; }
     <fieldset><legend>Select an image file</legend>
	 <p><b>File:</b> <input type="file" name="upload" /></p>
	 </fieldset>
	 
	 <input type="submit" name="submit" value="Submit" />
	 </div>
   </form>
<?php //Check if the form has been submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { //check for an uploaded file if (isset($_FILES['upload'])) { //validate the type, jpg or png $allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'); if (in_array($_FILES['upload']['type'], $allowed)) { //move the file over if (move_uploaded_file($_FILES['upload']['tmp_name'], "../uploads/{$_FILES['upload']['name']}")) { echo '

The file has been uploaded

'; }//end of move if } else { echo '

Uploaded file must be an image. File not uploaded.

'; }
		}//end of isset if
		
		//check for error
		if ($_FILES['upload']['error'] > 0)
		{
		   echo '<p class="error">The file could not be uploaded because:<strong>';
		   
		   
		   //print a message based upon the error
		   switch ($_FILES['upload']['error'])
		   {
		      case 1:
			     print 'The file exceeds the max_upload_size in php.ini.';
				 break;
			  case 2:
			     print 'The file exceeds the MAX_FILE_SIZE setting in the html form';
				 break;
			  case 3:
			     print 'The file has only been partially uploaded';
				 break;
			  case 4:
			     print 'No file was uploaded';
				 break;
			  case 6:
			     print 'No temporary folder was available';
				 break;
			  case 7:
			     print 'Unable to write to the hard disk';
				 break;
			  case 8:
			     print 'File upload stopped';
				 break;
			  default:
			     print'A system error occured';
				 break;
			}//end of switch
			
			print '<?strong></p>';
   }//end of error if
   
   //delete the file if it still exists
   if (file_exists ($_FILES['upload']['tmp_name']) && is_file ($_FILES['upload']['tmp_name']))
   {
      unlink ($_FILES['upload']['tmp_name']);
    }

}
  ?>[/php]

I’m sure this seems simple to most of you, but its giving me headaches!

Thanks…

You will need something like this to add to the mysql but you will need to make a connection first

[php]
//move the file over
if (move_uploaded_file($_FILES[‘upload’][‘tmp_name’], “…/uploads/{$_FILES[‘upload’][‘name’]}”))
{
echo ‘

The file has been uploaded

’;
          $uploaded = "../uploads/{$_FILES['upload']['name']}";
          $query = mysql_query("INSERT INTO `table_images`(`id`,`imagepath`) VALUE('','$uploaded')");

                 if (!$query) {
                echo 'Could not run query: ' . mysql_error();
                    exit;
                        }

             /* affected row warning debug */
              printf ("<br /> Updated records: %d\n", mysql_affected_rows());
                }[/php]

That is working brilliant! Thanks very much!

There are 2 more things concerning this script though.
First of all, is there a way to add the newest pic uploaded as the first in the db? As it is the pic gets added to the end, but it wil be for a gallery so newest pic should be displayed first. Or do I sort that out as I take the pics from the db/dir?

2.I need to resize the images too, aany pointers in doing this? So I would like them uploaded, resized then saved as the resized image. Or if you know a better way.

Thanks

Glen…

When you call the images back from the databse you can sort them by picture id ASC or DESC.

You can resize as you are uploading many tutorials on the net or use the search button.

Resizing the image as it is uploaded is not going so well!

Here is my upload script now

upload_image.php

[php]<DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://w3.org/TR//xhtml1-transitional.dtd”>

Upload an image .error{ font-weight: bold; color:#c00; }
     <fieldset><legend>Select an image file</legend>
	 <p><b>File:</b> <input type="file" name="upload" /></p>
	 <p><b>Animal Description</b><input type=text name="aname"></p>
	 </fieldset>
	 
	 <input type="submit" name="submit" value="Submit" />
	 </div>
   </form>
<?php
  include 'connect.php';
     //Check if the form has been submitted
	 if ($_SERVER['REQUEST_METHOD'] == 'POST')
	 {
	    //check for an uploaded file
		if (isset($_FILES['upload']))
		{
		   //validate the type, jpg or png
		   $allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png');
		   if (in_array($_FILES['upload']['type'], $allowed))
		   {
		      
		      //move the file over
             if (move_uploaded_file($_FILES['upload']['tmp_name'], "../uploads/{$_FILES['upload']['name']}"))
             {
				 echo '<p><em>The file has been uploaded</em></p>';

               $uploaded = "../uploads/{$_FILES['upload']['name']}";
			   $aname = $_POST['aname'];
               $query = mysql_query("INSERT INTO table_images VALUE(NULL, '$uploaded', '$aname')");

               if (!$query)
		       {
                  echo 'Could not run query: ' . mysql_error();
                  exit;
               }

               /* affected row warning debug */
               printf ("<br /> Updated records: %d\n", mysql_affected_rows());
    	     } 
	         else
     	     {
	            echo '<p><em>Uploaded file must be an image. File not uploaded.</em></p>';
		     }
		 
		  }     
		}//end of isset if
		
		//check for error
		if ($_FILES['upload']['error'] > 0)
		{
		   echo '<p class="error">The file could not be uploaded because:<strong>';
		   
		   
		   //print a message based upon the error
		   switch ($_FILES['upload']['error'])
		   {
		      case 1:
			     print 'The file exceeds the max_upload_size in php.ini.';
				 break;
			  case 2:
			     print 'The file exceeds the MAX_FILE_SIZE setting in the html form';
				 break;
			  case 3:
			     print 'The file has only been partially uploaded';
				 break;
			  case 4:
			     print 'No file was uploaded';
				 break;
			  case 6:
			     print 'No temporary folder was available';
				 break;
			  case 7:
			     print 'Unable to write to the hard disk';
				 break;
			  case 8:
			     print 'File upload stopped';
				 break;
			  default:
			     print'A system error occured';
				 break;
			}//end of switch
			
			print '<?strong></p>';
   }//end of error if
   
   //delete the file if it still exists
   if (file_exists ($_FILES['upload']['tmp_name']) && is_file ($_FILES['upload']['tmp_name']))
   {
      unlink ($_FILES['upload']['tmp_name']);
    }

}
  ?>[/php]

And here is a script i got of php.net for resizing images

resize.php

[php]// The file
$filename = ‘pdf.jpg’;

// Set a maximum height and width
$width = 300;
$height = 300;

// Content type
header(‘Content-Type: image/jpeg’);

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);[/php]

Can I use this script? If so how do I do this? I mean, how do I integrate this with my upload_image.php script and how do I make it take the uploaded image to resize?

Sorry if I am asking silly questions, but I cant get to grips with this!

Thanks…

Sponsor our Newsletter | Privacy Policy | Terms of Service