Solved

php upload image path to database and rename

Posted on 2010-11-12
7
842 Views
Last Modified: 2012-06-21
I have the following code which will resize an image into full size, thumb and mid and place them in files on the server.  The form before the user clicks upload ask the user to select a category where the image will go into.  Those options are pulled from the database.

How would i make it so that the path of the full size image and the thumb are entered into the database in the image table so that in the gallery i can call them and display them, I don't want to fill up the database with the actual images.

Also, is there a way to have it rename the images like image01.jpg, image02.jpg so that it will check to see what the last 2 digits are and count up so i can keep adding images?
<?php
							// retrieve information from the database

									$sql = "SELECT CatID FROM UserCategory Where UserID='".$_SESSION["UserID"]."'";
									$getCatID = mysql_query($sql);
							?>
						
                        <form id="form0" method="post" action="doUpload.php">
   							  <ul>
                              <li><select name="selectCat" id="selectCat" style="width:40%;">
                  				
								<?php while ($row = mysql_fetch_array($getCatID)){?>
				  					<option value="<?php echo $row["CatID"]; ?>"><?php echo $row["CatID"]; ?></option>
				  				<?php
								}
							   ?>
                			 </select></li>
                             <li><input id="SubmitBtn" name="SubmitBtn" type="submit" value="Upload Image"/></li></li>
                             </ul>
						</form>

Open in new window

<?php
	session_start();
	
	set_time_limit(300);
	
	if($_POST["uploadFile"] != ""){
		$fileExt = strrchr($_FILES['userfile']['name'], ".");
		
		if($fileExt != ".jpg" && $fileExt != ".gif"){
			$_SESSION["badFileType"] = "You cannot upload a file of type ".$fileExt;
		}else{
			$fileName = $_FILES ['userfile']['name'];
			
			if(!is_uploaded_file($_FILES['userfile']['tmp_name'])){
				echo "Problem: possible file upload attack!! ";
				exit;	
			}
			
			$counter = 80;
			
			$upfile = "upload/".$_POST["category"].$counter.".jpg";
			
			$newFileName = $_POST["category"].$counter.".jpg";
			
			if(!copy($_FILES['userfile']['tmp_name'], $upfile)){
				echo "Problem: file could not be copied to directory!!";
				exit;
			}
			$_SESSION["badFileType"] = "file uploaded successfully!";
		}
	}else{
		$_SESSION["badFileType"] = "";
	}
	
	/// RESIZING IMAGE
	
	$dir		= "./upload/";
	$middir		= "./mid/";
	$thdir		= "./thumb/";
	
	$img		= $newFileName;
	
	resizejpeg($dir, $middir, $img, 480, 360, "mid_");
	
	resizejpeg($dir, $thdir, $img, 160, 120, "th_");
	
	$_SESSION["badFileType"] .= "<br>file sucessfully resized!";
	
	header("Location: uploadimagesadmin.php");
	
	///////////////////////////////////////////////////////////
// function resizejpeg
//
//    creates a resized image based on the max width
//    specified as well as generates a thumbnail from
//    a rectangle cut from the middle of the image.
//
//    @dir    = directory image is stored in
//    @newdir = directory new image will be stored in
//    @img    = the image name
//    @max_w  = the max width of the resized image
//    @max_h  = the max height of the resized image
//    @prefix = the prefix of the resized image
//
///////////////////////////////////////////////////////////

function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $prefix)
{
   // set destination directory
   if (!$newdir) $newdir = $dir;

   // get original images width and height
   list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

   // make sure image is a jpeg
   if ($or_t == 2) 
   {
   
       // obtain the image's ratio
       $ratio = ($or_h / $or_w);

       // original image
       $or_image = imagecreatefromjpeg($dir.$img);

       // resize image?
       if ($or_w > $max_w || $or_h > $max_h) {

           // resize by height, then width (height dominant)
           if ($max_h < $max_w) {
               $rs_h = $max_h;
               $rs_w = $rs_h / $ratio;
           }
           // resize by width, then height (width dominant)
           else {
               $rs_w = $max_w;
               $rs_h = $ratio * $rs_w;
           }

           // copy old image to new image
           $rs_image = imagecreatetruecolor($rs_w, $rs_h);
           imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
       }
       // image requires no resizing
       else {
           $rs_w = $or_w;
           $rs_h = $or_h;

           $rs_image = $or_image;
       }

       // generate resized image
       imagejpeg($rs_image, $newdir.$prefix.$img, 100);

       return true;
   } 

   // Image type was not jpeg!
   else 
   {
       return false;
   }
}

?>

Open in new window

0
Comment
Question by:newmie22
  • 3
  • 3
7 Comments
 
LVL 14

Expert Comment

by:Scott Madeira
ID: 34119661
I don't think you need to save the path name in the database if you can organize your files correctly and you have the category name in the database.

You could have an /images directory and below that have subdirectories called full, thumb and mid.

In each of these subdirectories you could have subdirectories for each category.

so, if you have a "family" category your paths would be defined as

/images/full/family

/images/mid/family

/images/thumb/family

You wouldn't be storing anything except for the category name which you probably already have defined somewhere.

For image names I'd be inclined to go with a image_1.jpg image_2.jpg....image_1324.jpg, etc.  You can implode / explode the file name using the "_" and you aren't limited to only 100 images per category.

Don't have specific code to do this for you but it shouldn't be too difficult.

0
 

Author Comment

by:newmie22
ID: 34119680
Unfortunately we are required to use the database for this exercise which we then call using javascript and lightbox, and we are also limited to the 01, 02 file naming.
0
 
LVL 6

Expert Comment

by:Chorch
ID: 34120358
Hello,

this will determine the final filename:

$counter = 01;
$upfile = "upload/".$_POST["category"].$counter.".jpg";
$newFileName = $_POST["category"].$counter.".jpg";
$i = 1;
while (file_exists($upfile)) {
      $new_counter = sprintf("%02d",$i);
      $file_name = substr($newFileName, 0, strlen($pic_name)-6);
      $file_extension = substr($newFileName, strlen($newFileName)-6, strlen($newFileName));
      $frand = $file_name.$new_counter.$file_extension;
      $i++;
}
if (isset($new_counter)) {
      $upfile = "upload/".$_POST["category"].$new_counter.".jpg";
      $newFileName = $_POST["category"].$new_counter.".jpg";
}

Regards
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 6

Expert Comment

by:Chorch
ID: 34120376
Sorry, use this:

$counter = 01;
$upfile = "upload/".$_POST["category"].$counter.".jpg";
$newFileName = $_POST["category"].$counter.".jpg";
$i = 1;
while (file_exists($upfile)) {
      $i++;
      $new_counter = sprintf("%02d",$i);
      $file_name = substr($newFileName, 0, strlen($pic_name)-6);
      $file_extension = substr($newFileName, strlen($newFileName)-6, strlen($newFileName));
      $frand = $file_name.$new_counter.$file_extension;
      $upfile = "upload/".$_POST["category"].$new_counter.".jpg";
}
if (isset($new_counter)) {
      $upfile = "upload/".$_POST["category"].$new_counter.".jpg";
      $newFileName = $_POST["category"].$new_counter.".jpg";
}
0
 

Author Comment

by:newmie22
ID: 34120606
Thanks, that worked great for the needing 01, 02 part!  Do you know where i'd need to enter my sql statement to get the file path to upload to the server along with the category id, i've tried a few things based on some code i found but nothing adds to the database, the images upload and resize fine though.

$sql = "INSERT INTO ImageProject2 (ImageLocation, CatID) VALUES ('".$newFileName."', '".$_POST["category"]."')";
$result = mysql_query($sql);
0
 
LVL 6

Accepted Solution

by:
Chorch earned 500 total points
ID: 34120697
Hello,

CatID will probably be a medium_int type or similar... then it only allows numbers.

You can do 2 things:

a) alter this table and change the type to varchar(255) and store the category directly in the images table

b) Store the category ID in the images table, use: $sql = "INSERT INTO ImageProject2 (ImageLocation, CatID) VALUES ('".$newFileName."', '".$_POST["CatID"]."')";
 and then when getting the results of the images query, use also (assuming the categories table is called "categories"): LEFT JOIN categories ON categories.CatID=ImageProject2 .CatID

Regards
0
 

Author Closing Comment

by:newmie22
ID: 34120800
Great, thanks for all your help!
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Many companies are looking to get out of the datacenter business and to services like Microsoft Azure to provide Infrastructure as a Service (IaaS) solutions for legacy client server workloads, rather than continuing to make capital investments in h…
Never store passwords in plain text or just their hash: it seems a no-brainier, but there are still plenty of people doing that. I present the why and how on this subject, offering my own real life solution that you can implement right away, bringin…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now