Link to home
Start Free TrialLog in
Avatar of Jen765
Jen765

asked on

Upload multiple files and rename and re size them then send filepath to DB in PHP

What I am trying to do is upload multiple image files, re size them, rename them, and then upload them into separate tables in my database.

Is there a way to set a loop to upload, re size, rename, and then do a query to send them to separate tables in my db? I currently need to put each separate file into the tables "filepath1" "filepath2" "filepath3" etc.

I have a basic understanding of how to put it into a loop however how to get it into the separate tables in my DB seems to be more of the problem.

Jen
<?php require_once('includes/connection.php'); ?>
<?php 

if (isset($_GET["id"])) {
		$id = $_GET["id"];
		}
		
	$query = "SELECT * FROM pages WHERE id={$_GET['id']}";
	$page_set = mysql_query($query, $connection);
	$page = mysql_fetch_array($page_set);
    
	$uploaddir = "../graphics";
	
		if (empty($imgfile1)) {
		} else {

	$pext1 = getFileExtension($imgfile1_name);
	$pext1 = strtolower($pext1);

	if (($pext1 != "jpg")  && ($pext1 != "jpeg"))
    {
        print "<h1>ERROR</h1>Image Extension Unknown.<br>";
        print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg file.<br><br>";
        print "The first file you uploaded had the following extension: $pext1</p>\n";

        /*== delete uploaded file ==*/
		unlink($imgfile1);
        exit();
    }


	$imgsize1 = GetImageSize($imgfile1);
	
	if (($imgsize1[0] > 400) || ($imgsize1[1] > 300)) 
    {
      
        $tmpimg = tempnam("/tmp", "MKUP");
        system("djpeg $imgfile1 >$tmpimg");
        system("pnmscale -xy 400 300 $tmpimg | cjpeg -smoo 10 -qual 25 >$imgfile1");
        unlink($tmpimg);

    }

    /*== setup final file location and name ==*/
    /*== change spaces to underscores in filename  ==*/
	$imgfile1_name = $id . "a." . $pext1;
	$final_filename1 = str_replace(" ", "_", $imgfile1_name);
	$newfile1 = $uploaddir . "/$final_filename1";
	
	  if (is_uploaded_file($imgfile1))
    {

       if (!copy($imgfile1,"$newfile1")) 
       {
          print "Error Uploading File 1.";
          exit();
       }
     }

    /*== delete the temporary uploaded file ==*/
    unlink($imgfile1);
	
	$one = 'graphics/' . $final_filename1;
	
	$query = "UPDATE pages
	SET filepath1='$one'
	WHERE id={$id}";
	$result = mysql_query($query, $connection);

}
	
	
	
	if (empty($imgfile2)) {
		} else {

	$pext2 = getFileExtension($imgfile2_name);
	$pext2 = strtolower($pext2);

	if (($pext2 != "jpg")  && ($pext2 != "jpeg"))
    {
        print "<h1>ERROR</h1>Image Extension Unknown.<br>";
        print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg file.<br><br>";
        print "The second file you uploaded had the following extension: $pext2</p>\n";
		unlink($imgfile2);
        exit();
    }


	$imgsize2 = GetImageSize($imgfile2);
	
	if (($imgsize2[0] > 400) || ($imgsize2[1] > 300)) 
    {
     $tmpimg = tempnam("/tmp", "MKUP");
        system("djpeg $imgfile2 >$tmpimg");
        system("pnmscale -xy 400 300 $tmpimg | cjpeg -smoo 10 -qual 25 >$imgfile2");
        unlink($tmpimg);

    }

	$imgfile2_name = $id . "b." . $pext2;
	$final_filename2 = str_replace(" ", "_", $imgfile2_name);
	$newfile2 = $uploaddir . "/$final_filename2";
	
	  if (is_uploaded_file($imgfile2))
    {

       if (!copy($imgfile2,"$newfile2")) 
       {
          print "Error Uploading File 2.";
          exit();
       }
     }

    unlink($imgfile2);
	
	$two = 'graphics/' . $final_filename2;
	
	$query = "UPDATE pages
	SET filepath2='$two'
	WHERE id={$id}";
	$result = mysql_query($query, $connection);

}



if (empty($imgfile3)) {
		} else {

	$pext3 = getFileExtension($imgfile3_name);
	$pext3 = strtolower($pext3);

	if (($pext3 != "jpg")  && ($pext3 != "jpeg"))
    {
        print "<h1>ERROR</h1>Image Extension Unknown.<br>";
        print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg file.<br><br>";
        print "The third file you uploaded had the following extension: $pext3</p>\n";

        /*== delete uploaded file ==*/
		unlink($imgfile3);
        exit();
    }


	$imgsize3 = GetImageSize($imgfile3);
	
	if (($imgsize3[0] > 400) || ($imgsize3[1] > 300)) 
    {
      
        $tmpimg = tempnam("/tmp", "MKUP");
        system("djpeg $imgfile3 >$tmpimg");
        system("pnmscale -xy 400 300 $tmpimg | cjpeg -smoo 10 -qual 25 >$imgfile3");
        unlink($tmpimg);

    }

    /*== setup final file location and name ==*/
    /*== change spaces to underscores in filename  ==*/
	$imgfile3_name = $id . "c." . $pext3;
	$final_filename3 = str_replace(" ", "_", $imgfile3_name);
	$newfile3 = $uploaddir . "/$final_filename3";
	
	  if (is_uploaded_file($imgfile3))
    {

       if (!copy($imgfile3,"$newfile3")) 
       {
          print "Error Uploading File 3.";
          exit();
       }
     }

    /*== delete the temporary uploaded file ==*/
    unlink($imgfile3);
	
	$three = 'graphics/' . $final_filename3;
	
	$query = "UPDATE pages
	SET filepath3='$three'
	WHERE id={$id}";
	$result = mysql_query($query, $connection);
}
	

if($result){
echo "<br><span class=\"style1\">Photos were uploaded. You will be redirected in a moment.</span>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=admin.php\">";
}
	
  


?>
<?php
    /*== FUNCTIONS ==*/

    function getFileExtension($str) {

        $i = strrpos($str,".");
        if (!$i) { return ""; }

        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);

        return $ext;

    }
?>
<?php require("includes/footer.php"); ?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mark Brady
Mark Brady
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jen765
Jen765

ASKER

Perfect. I actually was able to get the loop I just couldn't figure out how to get the table name to auto increment. Thank you!
Avatar of Jen765

ASKER

This is how my code ended up looking like. Not extremely pretty but functional.
<?php 

if (isset($_GET["id"])) {
		$id = $_GET["id"];
		}
		
		 //This function separates the files extension from the rest of the file name and returns it 
 function findexts ($filename) 
 { 
 $filename = strtolower($filename) ; 
 $exts = split("[/\\.]", $filename) ; 
 $n = count($exts)-1; 
 $exts = $exts[$n]; 
 return $exts; 
 } 
 
?>

<?php
/* $_FILES array will be along these lines:
Array
(
    [uploadFile] => Array
        (
            [name] => Array
                (
                    [0] =>
                    [1] =>
                    [2] =>
                    [3] =>
                    [4] =>
                )

            [type] => Array
                (
                    [0] =>
                    [1] =>
                    [2] =>
                    [3] =>
                    [4] =>
                )

            [tmp_name] => Array
                (
                    [0] =>
                    [1] =>
                    [2] =>
                    [3] =>
                    [4] =>
                )

            [error] => Array
                (
                    [0] => 4
                    [1] => 4
                    [2] => 4
                    [3] => 4
                    [4] => 4
                )

            [size] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 0
                    [3] => 0
                    [4] => 0
                )

        )

)
*/
//FORM PROCESSING
$upload_ok = false;
$uploads = 0;
$i = 1;
$result = '';

//change this to your uploads folder
$target = 'graphics/';

//array of upload jobs
$arr_uploads = false;

//array of permitted extensions
$arr_allowed_ext = array('gif','GIF','jpg','JPG','jpeg','JPEG','png','PNG');

if( !empty($_FILES) ) {

      //get info of files to upload
      foreach($_FILES['uploadFile']['name'] as $k => $v) {
            if(!empty($v)) $arr_uploads[$k]['name'] = $v;
      }
      
      //number of files to upload
      $t_jobs = count($arr_uploads);      
      $result .= "$t_jobs files uploaded.<br />";
      
      if( !empty($arr_uploads) ) {
            
            unset ($k);
            unset ($v);
            
            foreach($arr_uploads as $k => $v) {
            
                  //check format
                  $format_ok = false;
                  
                  $this_format = $_FILES['uploadFile']['type'][$k];
                  
                  foreach($arr_allowed_ext as $v2) {
                        if( strpos($this_format,$v2) ) $format_ok = true;
                  }
                  
                  if(!$format_ok) {
                        $result .= "[format error] File[$k:$v] - format is not supported.<br />";
                        unset($arr_uploads[$k]);
                  }
                  
                  if( isset($arr_uploads[$k]) ) {
				  
				  
				  //This line grabs the image so that it can be resized
				  $imgsize = GetImageSize ($_FILES['uploadFile']['tmp_name'][$k]);
				  
	//This line resizes the image if the height and width are bigger than I want
	if (($imgsize[0] > 400) || ($imgsize[1] > 300)) 
    {
      
	  $imgfile = $_FILES['uploadFile']['tmp_name'][$k];
	  
        $tmpimg = tempnam("/tmp", "MKUP");
        system("djpeg $imgfile >$tmpimg");
        system("pnmscale -xy 400 300 $tmpimg | cjpeg -smoo 10 -qual 85 >$imgfile");
        unlink($tmpimg);

    }
	
	  
				  		 //This applies the function to our file  
 $ext = findexts ($_FILES['uploadFile']['name'][$k]) ;
 
 //This line creates the file name
 $fname = $id . "_" . $i;
 
 $name = $fname . ".";
 
 $file_name = $name.$ext; 
 
 $db = "graphics/" . $file_name;

//This combines the directory, the file name, and the extension
$target_path = $target . $file_name; 
                        
                         $upload_ok = move_uploaded_file($_FILES['uploadFile']['tmp_name'][$k], $target_path);
                        
                              if($upload_ok) {
                                    
                                    $result .= "[file upload] File[$k:$file_name] uploaded.<br />";
                                    $arr_uploads[$k]['name'] = $file_name;
                                    $arr_uploads[$k]['link'] = $target_path;
                                    
                                    $table_name = "filepath".$i;
									
									$query = "UPDATE pages
									SET $table_name='$db'
									WHERE id={$id}";
									
									$results = mysql_query($query, $connection);
									
									if ($results) {
									echo $db . " was added to the db. <br>";
									}
									
									$uploads++;
									$i++;
									
                              } else{
                              
                                    $result .= "[upload error] File[$k:$file_name] There was an error uploading this file, please try again!<br />";
                                    
                              }
                              
                  }//end if job isset
                        
            }//end foreach
      
      }//end jobs not empty
      
}//end form processing.


	
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>J&M Administrator</title>

<script language="JavaScript" type="text/javascript"> 
function getInfo() { 
doyou = confirm("Please be patient these files will take a minute to upload. Do not hit the back button."); //Your question. 
if (doyou == true) 
form.submit();
else 
if (doyou == false) 
history.go(-1); //After answered No, the action. (In < this < case, it sends you back 1 page!) 
} 
</script> 


</head>

<body>

<?php
if($result != '') echo '<p>Result: '.$result.'</p>';

if( $uploads == 0 ) { ?>

<form enctype="multipart/form-data" action="" method="POST">
      <table width="98%">
        <tr>
            <td width="34%" height="26">
              <div align="right"><font color="#FF0000" size="-2" face="Arial, Helvetica, sans-serif">Choose
                  a file(s) to upload:</font></div></td>
            <td width="66%"> <div align="left">
                  <input name="uploadFile[]" type="file" id="uploadFile[]" />
             
              </div></td>
        </tr>
        <tr>
            <td> <div align="right"> </div></td>
            <td> <div align="left">
                  <input name="uploadFile[]" type="file" id="uploadFile[]" />
                  
              </div></td>
        </tr>
        <tr>
            <td> <div align="right"> </div></td>
            <td> <div align="left">
                  <input name="uploadFile[]" type="file" id="uploadFile[]" />
                  
              </div></td>
        </tr>
        <tr>
            <td> <div align="right"> </div></td>
            <td> <div align="left">
                  <input name="uploadFile[]" type="file" id="uploadFile[]" />
                  
              </div></td>
        </tr>
        <tr>
            <td> <div align="right"></div></td>
            <td> <div align="left">
                  <input name="uploadFile[]" type="file" id="uploadFile[]" />
                  
              </div></td>
        </tr>
        <tr>
            <td><div align="right"> </div></td>
            <td> <div align="left">
                  <input name="submit" type="submit" value="Upload files" onClick="getInfo()" />
              </div></td>
        </tr>
      </table>
</form>
<?php //end uploads
            } 
?>

</span></div>
</body>
</html>

Open in new window