Solved

php upload image path to database and rename

Posted on 2010-11-12
7
838 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article describes some very basic things about SQL Server filegroups.
Creating and Managing Databases with phpMyAdmin in cPanel.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 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

21 Experts available now in Live!

Get 1:1 Help Now