Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 885
  • Last Modified:

php upload image path to database and rename

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
newmie22
Asked:
newmie22
  • 3
  • 3
1 Solution
 
Scott MadeiraCommented:
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
 
newmie22Author Commented:
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
 
ChorchCommented:
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
Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

 
ChorchCommented:
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
 
newmie22Author Commented:
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
 
ChorchCommented:
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
 
newmie22Author Commented:
Great, thanks for all your help!
0

Featured Post

Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now