需要帮助使用php将多个图像上传到不同的文件夹,并在mysql数据库中存储文件名


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

我有一个代码,将不同的图像文件上传到服务器上的不同文件夹,并在mysql数据库的不同字段中存储文件名。我已经写了代码,它的工作很好。我需要的帮助是如何编写代码,而不是使用多个代码块来重新调整大小和上传每个图像,一个代码块将能够重新调整多个图像的大小,但仍然将多个图像上传到各自不同的文件夹中,同时仍然在mysql数据库的不同字段中存储不同的文件名。如有任何帮助,我将不胜感激。

下面是php代码:
<?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));
}
?>
这是表单的代码:
<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>

创建一个接受post FILE的函数,并在调整大小和写入后返回一个文件信息数组。然后在文件验证后对每个post File调用它。如果它返回一个没有错误的信息数组。然后做数据库工作人员这里是一个例子

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
  }
}