Need help using php to upload multiple images to different folders and store file names in mysql datatbase

Michael Agbogidi

I have a code that uploads different image files to different folders on the server and stores the file names in different fields in a mysql database. I have written the codes and its working fine. The help i need is how to write the codes such that instead of using multiple codes blocks for re-sizing and uploading each image, one code block would be able to re-size multiple images but still upload the multiple images into their respective different folders and at the same time still store the different file names in different fields in the mysql database. Any help would be greatly appreciated.

Below is the php code:

<?php
function getExtension($str) {

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

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


define ("MAX_SIZE","2048");

 $errors=0;

{
 $image =$_FILES["passport"]["name"];
 $uploadedfile = $_FILES['passport']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['passport']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
  {
    echo ' Unknown Image extension ';
    $errors=1;
  }
 else
  {
   $size=filesize($_FILES['passport']['tmp_name']);

   // Check if file was uploaded
if( ! isset($_FILES['passport']) || ! is_uploaded_file($_FILES['passport']['tmp_name']))
        exit('No file uploaded or Your passport has exceeded the size limit of 2Mb. Click the back botton on your browser to re-enter the right size of image.');

  if ($size > MAX_SIZE*1024)
  {
    echo "Your passport image has exceeded the size limit";
    $errors=1;
  }

    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES['passport']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);
    }
    else if($extension=="png")
    {
    $uploadedfile = $_FILES['passport']['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);
    }
    else 
    {
    $src = imagecreatefromgif($uploadedfile);
    }

list($width,$height)=getimagesize($uploadedfile);

$newwidth=1120;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

//$set['passport'] = "'" . $pix . "'";
$pix= $_FILES['passport']['name'];
$kaboom = explode(".", $pix);
$pixExt = end($kaboom);
$passport= rand()."_".time().".".$pixExt;

$target = "passport/". $passport;

imagejpeg($tmp,$target,100);
}
  }
}

{
 $image =$_FILES["birthcert"]["name"];
 $uploadedfile = $_FILES['birthcert']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['birthcert']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
  {
    echo ' Unknown Image extension ';
    $errors=1;
  }
 else
  {
   $size=filesize($_FILES['birthcert']['tmp_name']);

   // Check if file was uploaded
if( ! isset($_FILES['birthcert']) || ! is_uploaded_file($_FILES['birthcert']['tmp_name']))
        exit('No file uploaded or Your birth certificate has exceeded the size limit of 2Mb. Click the back botton on your browser to re-enter the right size of image.');

  if ($size > MAX_SIZE*1024)
  {
    echo "Your birth certificate image has exceeded the size limit";
    $errors=1;
  }

    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES['birthcert']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);
    }
    else if($extension=="png")
    {
    $uploadedfile = $_FILES['birthcert']['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);
    }
    else 
    {
    $src = imagecreatefromgif($uploadedfile);
    }

list($width,$height)=getimagesize($uploadedfile);

$newwidth=1120;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

//$set['passport'] = "'" . $pix . "'";
$pix= $_FILES['birthcert']['name'];
$kaboom = explode(".", $pix);
$pixExt = end($kaboom);
$birthcert= rand()."_".time().".".$pixExt;

$target = "birthcert/". $birthcert;

imagejpeg($tmp,$target,100);

}
  }
}

{
 $image =$_FILES["lastacadreport"]["name"];
 $uploadedfile = $_FILES['lastacadreport']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['lastacadreport']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
  {
    echo ' Unknown Image extension ';
    $errors=1;
  }
 else
  {
   $size=filesize($_FILES['lastacadreport']['tmp_name']);

   // Check if file was uploaded
if( ! isset($_FILES['lastacadreport']) || ! is_uploaded_file($_FILES['lastacadreport']['tmp_name']))
        exit('No file uploaded or Your last academic report has exceeded the size limit of 2Mb. Click the back botton on your browser to re-enter the right size of image.');

  if ($size > MAX_SIZE*1024)
  {
    echo "Your last academic report image has exceeded the size limit";
    $errors=1;
  }

    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES['lastacadreport']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);
    }
    else if($extension=="png")
    {
    $uploadedfile = $_FILES['lastacadreport']['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);
    }
    else 
    {
    $src = imagecreatefromgif($uploadedfile);
    }

list($width,$height)=getimagesize($uploadedfile);

$newwidth=1120;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

//$set['passport'] = "'" . $pix . "'";
$pix= $_FILES['lastacadreport']['name'];
$kaboom = explode(".", $pix);
$pixExt = end($kaboom);
$lastacadreport= rand()."_".time().".".$pixExt;

$target = "lastacadreport/". $lastacadreport;

imagejpeg($tmp,$target,100);

}
  }
}

{
 $image =$_FILES["testimonial"]["name"];
 $uploadedfile = $_FILES['testimonial']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['testimonial']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
  {
    echo ' Unknown Image extension ';
    $errors=1;
  }
 else
  {
   $size=filesize($_FILES['testimonial']['tmp_name']);

   // Check if file was uploaded
if( ! isset($_FILES['testimonial']) || ! is_uploaded_file($_FILES['testimonial']['tmp_name']))
        exit('No file uploaded or Your testimonial has exceeded the size limit of 2Mb. Click the back botton on your browser to re-enter the right size of image.');

  if ($size > MAX_SIZE*1024)
  {
    echo "Your testimonial image has exceeded the size limit";
    $errors=1;
  }

    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES['testimonial']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);
    }
    else if($extension=="png")
    {
    $uploadedfile = $_FILES['testimonial']['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);
    }
    else 
    {
    $src = imagecreatefromgif($uploadedfile);
    }

list($width,$height)=getimagesize($uploadedfile);

$newwidth=1120;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

//$set['passport'] = "'" . $pix . "'";
$pix= $_FILES['testimonial']['name'];
$kaboom = explode(".", $pix);
$pixExt = end($kaboom);
$testimonial= rand()."_".time().".".$pixExt;

$target = "testimonial/". $testimonial;

imagejpeg($tmp,$target,100);

}
  }
}

{
 $image =$_FILES["lastresult"]["name"];
 $uploadedfile = $_FILES['lastresult']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['lastresult']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
  {
    echo ' Unknown Image extension ';
    $errors=1;
  }
 else
  {
   $size=filesize($_FILES['lastresult']['tmp_name']);

   // Check if file was uploaded
if( ! isset($_FILES['lastresult']) || ! is_uploaded_file($_FILES['lastresult']['tmp_name']))
        exit('No file uploaded or Your last result has exceeded the size limit of 2Mb. Click the back botton on your browser to re-enter the right size of image.');

  if ($size > MAX_SIZE*1024)
  {
    echo "Your last result image has exceeded the size limit";
    $errors=1;
  }

    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES['lastresult']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);
    }
    else if($extension=="png")
    {
    $uploadedfile = $_FILES['lastresult']['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);
    }
    else 
    {
    $src = imagecreatefromgif($uploadedfile);
    }

list($width,$height)=getimagesize($uploadedfile);

$newwidth=1120;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

//$set['passport'] = "'" . $pix . "'";
$pix= $_FILES['lastresult']['name'];
$kaboom = explode(".", $pix);
$pixExt = end($kaboom);
$lastresult= rand()."_".time().".".$pixExt;

$target = "lastresult/". $lastresult;

imagejpeg($tmp,$target,100);

}
  }
}

{
 $image =$_FILES["transfercert"]["name"];
 $uploadedfile = $_FILES['transfercert']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['transfercert']['name']);
  $extension = getExtension($filename);
  $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
  {
    echo ' Unknown Image extension ';
    $errors=1;
  }
 else
  {
   $size=filesize($_FILES['transfercert']['tmp_name']);

   // Check if file was uploaded
if( ! isset($_FILES['transfercert']) || ! is_uploaded_file($_FILES['transfercert']['tmp_name']))
        exit('No file uploaded or Your transfer certificate has exceeded the size limit of 2Mb. Click the back botton on your browser to re-enter the right size of image.');

  if ($size > MAX_SIZE*1024)
  {
    echo "Your transfer certificate image has exceeded the size limit";
    $errors=1;
  }

    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES['transfercert']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);
    }
    else if($extension=="png")
    {
    $uploadedfile = $_FILES['transfercert']['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);
    }
    else 
    {
    $src = imagecreatefromgif($uploadedfile);
    }

list($width,$height)=getimagesize($uploadedfile);

$newwidth=1120;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

//$set['passport'] = "'" . $pix . "'";
$pix= $_FILES['transfercert']['name'];
$kaboom = explode(".", $pix);
$pixExt = end($kaboom);
$transfercert= rand()."_".time().".".$pixExt;

$target = "transfercert/". $transfercert;

imagejpeg($tmp,$target,100);

}
  }
imagedestroy($src);
imagedestroy($tmp);
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "onlineapp")) {
  $insertSQL = sprintf("INSERT INTO wp1_onlineform (surname, othernames, sex, dateofbirth, placeofbirth, stateoforigin, nameofparent, occupationofparent, officeadd, officephone, homephone, homeaddress, previousschool, addofprevschl, highestclass, admissionclass, passport, birthcert, acadreport, testimonial, lastresult, transfercert) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, '$passport', '$birthcert', '$lastacadreport', '$testimonial', '$lastresult', '$transfercert')",
                       GetSQLValueString($_POST['surname'], "text"),
                       GetSQLValueString($_POST['othernames'], "text"),
                       GetSQLValueString($_POST['sex'], "text"),
                       GetSQLValueString($_POST['dob'], "text"),
                       GetSQLValueString($_POST['placeofbirth'], "text"),
                       GetSQLValueString($_POST['state'], "text"),
                       GetSQLValueString($_POST['parentname'], "text"),
                       GetSQLValueString($_POST['occupation'], "text"),
                       GetSQLValueString($_POST['officeaddress'], "text"),
                       GetSQLValueString($_POST['officephone'], "text"),
                       GetSQLValueString($_POST['homephone'], "text"),
                       GetSQLValueString($_POST['homeaddress'], "text"),
                       GetSQLValueString($_POST['prevschoolname'], "text"),
                       GetSQLValueString($_POST['prevschooladd'], "text"),
                       GetSQLValueString($_POST['highestclass'], "text"),
                       GetSQLValueString($_POST['admissionclass'], "text"));

  mysql_select_db($database_connPacific, $connPacific);
  $Result1 = mysql_query($insertSQL, $connPacific) or die(mysql_error());

  $insertGoTo = "confirm.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?>

This is the code for the form:

<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="onlineapp">
              <table width="760" border="0" cellspacing="0" cellpadding="10">
                <tr>
                  <td width="276" id="maintext">Surname:</td>
                  <td width="444" id="maintext2"><label for="surname"></label>
                  <input name="surname" type="text" class="textfield" id="surname" size="45"></td>
                </tr>
                <tr>
                  <td id="maintext">Other names:</td>
                  <td id="maintext2"><input name="othernames" type="text" class="textfield" id="othernames" size="45"></td>
                </tr>
                <tr>
                  <td id="maintext">Sex:</td>
                  <td id="maintext2"><select name="sex" class="textfield" id="sex">
                    <option selected>- Select One -</option>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                  </select></td>
                </tr>
                <tr>
                  <td id="maintext">Date of Birth:</td>
                  <td id="maintext2"><input name="dob" type="text" class="textfield" id="dob" size="20"> 
                    (dd-mm-yyyy)</td>
                </tr>
                <tr>
                  <td id="maintext">Place of Birth:</td>
                  <td id="maintext2"><input name="placeofbirth" type="text" class="textfield" id="placeofbirth" size="30"></td>
                </tr>
                <tr>
                  <td id="maintext">State of Origin:</td>
                  <td id="maintext2"><input name="state" type="text" class="textfield" id="state" size="30"></td>
                </tr>
                <tr>
                  <td id="maintext">Name of Parent/Guardian:</td>
                  <td id="maintext2"><input name="parentname" type="text" class="textfield" id="parentname" size="45"></td>
                </tr>
                <tr>
                  <td id="maintext">Occupation of Parent/Guardian:</td>
                  <td><input name="occupation" type="text" class="textfield" id="occupation" size="45"></td>
                </tr>
                <tr>
                  <td id="maintext">Office Address  of Parent/Guardian:</td>
                  <td id="maintext2"><input name="officeaddress" type="text" class="textfield" id="officeaddress" size="70"></td>
                </tr>
                <tr>
                  <td id="maintext">Office Phone:</td>
                  <td id="maintext2"><input name="officephone" type="text" class="textfield" id="officephone" size="30"></td>
                </tr>
                <tr>
                  <td id="maintext">Home Phone:</td>
                  <td id="maintext2"><input name="homephone" type="text" class="textfield" id="homephone" size="30"></td>
                </tr>
                <tr>
                  <td id="maintext">Home Address</td>
                  <td id="maintext2"><input name="homeaddress" type="text" class="textfield" id="homeaddress" size="70"></td>
                </tr>
                <tr>
                  <td id="maintext">Name of Previous School:</td>
                  <td id="maintext2"><input name="prevschoolname" type="text" class="textfield" id="prevschoolname" size="45"></td>
                </tr>
                <tr>
                  <td id="maintext">Address of Previous School:</td>
                  <td id="maintext2"><input name="prevschooladd" type="text" class="textfield" id="prevschooladd" size="70"></td>
                </tr>
                <tr>
                  <td id="maintext">Highest Clsss Passed at Previous School:</td>
                  <td id="maintext2"><input name="highestclass" type="text" class="textfield" id="highestclass" size="30"></td>
                </tr>
                <tr>
                  <td id="maintext">Class to Which Admission is being Sougth:</td>
                  <td id="maintext2"><input name="admissionclass" type="text" class="textfield" id="admissionclass" size="30"></td>
                </tr>
                <tr>
                  <td id="maintext">&nbsp;</td>
                  <td id="maintext2"><label for="passport"><strong>Note: All uploads must be below 2Mb</strong></label></td>
                </tr>
                <tr>
                  <td id="maintext">Passport Photo:</td>
                  <td id="maintext2"><input type="file" name="passport" id="passport"></td>
                </tr>
                <tr>
                  <td id="maintext">Birth Certificate:</td>
                  <td id="maintext2"><input type="file" name="birthcert" id="birthcert"></td>
                </tr>
                <tr>
                  <td id="maintext">Last academic report from child&rsquo;s current school:</td>
                  <td id="maintext2"><input type="file" name="lastacadreport" id="lastacadreport"></td>
                </tr>
                <tr>
                  <td id="maintext">Character testimonial from current school:</td>
                  <td id="maintext2"><input type="file" name="testimonial" id="testimonial"></td>
                </tr>
                <tr>
                  <td id="maintext">&nbsp;</td>
                  <td id="maintext2"><strong>For Transfer Students Only</strong></td>
                </tr>
                <tr>
                  <td id="maintext">Last Result from Former School::</td>
                  <td id="maintext2"><input type="file" name="lastresult" id="lastresult"></td>
                </tr>
                <tr>
                  <td id="maintext">Transfer Certificate From Former School:</td>
                  <td id="maintext2"><input type="file" name="transfercert" id="transfercert"></td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td id="maintext2"><input name="button" type="submit" class="button" id="button" value="Submit Form"></td>
                </tr>
              </table>
              <input type="hidden" name="MM_insert" value="onlineapp">
            </form>
Fisherman

Create a function that accept a post FILE and after resizing and writing its return an array of file information. then call it for every post File after file validation. if its return an array of information with none error. then do the database staff here is an example

function imageStaff($file){
// here resizing an writing staff

// return an array with index error and file information if no error then set this index to empty
}

//call here with post file
if(valid($_FILES['your_file')){ // valid is another function of yours to check if file size is ok, or check uploaded file_type etc
  $array = imageStaff($_FILES['your_file']);
 if(empty($array['error'])){
   //do the db staff
  }

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Upload multiple images and save names in database PHP MySQL

Upload images to different folders in s3 (by album names) using Shrine gem

HTML multiple file upload from different folders

Upload Multiple Images with PHP and put it into MYSQL Database

Swift How to upload images into firebase with different file names?

php upload images and save file name to mysql

Multiple file upload and location store using laravel

multiple image upload to different column php mysql

PHP multiple file upload with different keys

Ruby on Rails: Help in multiple image upload using paperclip with different process

How to store images in mysql database using php

PHP upload multiple files with different input field names

How to upload image to multiple folders using core php only?

Names and links to images in multiple folders on Google Drive

In multiple files upload(PHP/Mysql), the images are stored in single column. Want to store each image in single row with same id

Multer: upload different file types in different folders

Multiple Images upload with different titles

Rename multiple folders with different names in Java

Need help while generating reference no using php and Mysql

Need help on insert comma separated data in mysql database using PHP

Upload Multiple Files From DIfferent Folders

Could not upload multiple file into folder using PHP

Need little help php mysql

How to store file path using PHP file upload

UWP how to upload a list of images from different folders to different pivotItems

Join data in different folders considering the file names

Need Batch File/Script To Find Multiple Usernames Using Their Machine Names

How to upload csv file using php into mysql?

Using PHP to upload file add path to MySQL