问题以相同的形式上传并重命名多个文件

问题描述 投票:0回答:1

我目前正在使用PHP / Mysqli处理具有多个文件上传(一个图像和多个pdf)的表单。当我填写信息时,信息会记录到数据库中,但文件名未重命名,名为“ uploads”的目标文件夹仍然为空。我尝试了许多php脚本,但仍然无法正常工作。任何帮助将不胜感激。请在下面的代码中找到。谢谢。

形式的代码

<form method="post" enctype="multipart/form-data" name="form1" id="form1">
  <table align="center">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Email:</td>
      <td><input type="text" name="email" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Nom:</td>
      <td><input type="text" name="nom" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Prenom:</td>
      <td><input type="text" name="prenom" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Localisation:</td>
      <td><select name="localisation" id="localisation">
                                        <option value=""></option>
                                          <option value="Luxembourg - Luxembourg" >Luxembourg - Luxembourg</option>
                                          <option value="Lituanie - Lithuania" >Lituanie - Lithuania</option>
                                          <option value="Liechtenstein - Liechtenstein" >Liechtenstein - Liechtenstein</option>
                                          <option value="Libye - Libyan Arab Jamahiriya" >Libye - Libyan Arab Jamahiriya</option>
                                          <option value="Liberia - Liberia" >Liberia - Liberia</option>
                                          <option value="Liban - Lebanon" >Liban - Lebanon</option>
                                          <option value="Lettonie - Latvia" >Lettonie - Latvia</option>
                                          <option value="Lesotho - Lesotho" >Lesotho - Lesotho</option>
                                          <option value="Albanie - Albania" >Albanie - Albania</option>
                                          <option value="Afrique du Sud - South Africa" >Afrique du Sud - South Africa</option>
                                          <option value="Afghanistan - Afghanistan" >Afghanistan - Afghanistan</option>
                                          <option value="" ></option>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Pays d'Origine:</td>
      <td><select name="pays" id="pays">
                                            <option value=""></option>
                                              <option value="Togo - Togo" >Togo - Togo</option>
                                          <option value="Sénégal - Senegal" >Sénégal - Senegal</option>
                                          <option value="Niger - Niger" >Niger - Niger</option>
                                          <option value="Mali - Mali" >Mali - Mali</option>
                                          <option value="Guinée - Guinea" >Guinée - Guinea</option>
                                          <option value="Côte d'Ivoire - Ivory Coast" >Côte d'Ivoire - Ivory Coast</option>
                                          <option value="Burkina Faso - Burkina Faso" >Burkina Faso - Burkina Faso</option>
                                          <option value="Bénin - Benin" >Bénin - Benin</option>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Secteur de travail 1:</td>
      <td><select name="secteur1" id="secteur1">
                                            <option value=""></option>
                                              <option value="Autres - Others" >Autres - Others</option>
                                          <option value="Sécurité  - Security " >Sécurité  - Security </option>
                                          <option value="Sciences - Sciences " >Sciences - Sciences </option>
                                          <option value="Vente - Sales " >Vente - Sales </option>
                                          <option value="Commerce de détail  - Retail " >Commerce de détail  - Retail </option>
                                          <option value="Impression et édition  - Printing and publishing  " >Impression et édition  - Printing and publishing  </option>
                                          <option value="Marketing et communications - Marketing and communications " >Marketing et communications - Marketing and communications </option>
                                          <option value="" ></option>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Photo:</td>
      <td><input name="photo" type="file" id="photo" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Titre CV/Competences:</td>
      <td><input type="text" name="titre_cv1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Fichier CV:</td>
      <td><input type="file" name="cv1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Langue CV:</td>
      <td><input type="text" name="langue_cv1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Diplôme 1:</td>
      <td><input type="text" name="dip1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Université d'obtention:</td>
      <td><input type="text" name="obtention1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Fichier diplôme 1:</td>
      <td><input type="file" name="fichier1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td><input type="submit" value="Insert record" name="submit"/></td>
    </tr>
  </table>
  <input type="hidden" name="id" value="" />
  <input type="hidden" name="todays_date" value="<?php echo date("Y-m-d");  ?>" />
  <input type="hidden" name="MM_insert" value="form1" />
</form>

将输入插入数据库的PHP代码

    <?php require_once('Connections/conn_i.php'); ?>
<?php
if ((((isset($_POST["MM_insert"]))?$_POST["MM_insert"]:"") != "")) {
  $InsertQuery = new WA_MySQLi_Query($conn_i);
  $InsertQuery->Action = "insert";
  $InsertQuery->Table = "infos";
  $InsertQuery->bindColumn("id", "d", "".((isset($_POST["id"]))?$_POST["id"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("email", "s", "".((isset($_POST["email"]))?$_POST["email"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("nom", "s", "".((isset($_POST["nom"]))?$_POST["nom"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("prenom", "s", "".((isset($_POST["prenom"]))?$_POST["prenom"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("localisation", "s", "".((isset($_POST["localisation"]))?$_POST["localisation"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("pays", "s", "".((isset($_POST["pays"]))?$_POST["pays"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("secteur1", "s", "".((isset($_POST["secteur1"]))?$_POST["secteur1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("photo", "s", "".((isset($_FILES["photo"]))?$_FILES["photo"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("titre_cv1", "s", "".((isset($_POST["titre_cv1"]))?$_POST["titre_cv1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("cv1", "s", "".((isset($_FILES["cv1"]))?$_FILES["cv1"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("langue_cv1", "s", "".((isset($_POST["langue_cv1"]))?$_POST["langue_cv1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("dip1", "s", "".((isset($_POST["dip1"]))?$_POST["dip1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("obtention1", "s", "".((isset($_POST["obtention1"]))?$_POST["obtention1"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("fichier1", "s", "".((isset($_FILES["fichier1"]))?$_FILES["fichier1"]["name"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->bindColumn("todays_date", "t", "".((isset($_POST["todays_date"]))?$_POST["todays_date"]:"")  ."", "WA_DEFAULT");
  $InsertQuery->saveInSession("");
  $InsertQuery->execute();
  $InsertGoTo = "Success.php";
  if (function_exists("rel2abs")) $InsertGoTo = $InsertGoTo?rel2abs($InsertGoTo,dirname(__FILE__)):"";
  $InsertQuery->redirect($InsertGoTo);
}
?>

用于重命名并保存无效文件的代码!

    <?php
if (isset($_POST['photo'])) {
    $upload_error_codes=array("",
        "The uploaded file exceeds the upload_max_filesize directive in php.ini.","",
        "The uploaded file was only partially uploaded.",
        "No file was uploaded.","Missing a temporary folder.",
        "Failed to write file to disk.","File upload stopped by extension.");
    $allowed_ext_string="jpeg,jpg";
    $allowed_extensions=explode(",",$allowed_ext_string);
    $upload_status = "";
    $allowed_size =  2+0;
    $success_page = "Success.php";
    $thumbs_dir = "";
    $resize_image = "yes";
    $resize_width = 150+0;
    $resize_height = 200+0;
    $thumb_width = +0;
    $thumb_height = +0;     
    $make_thumbs = "";
    $thumb_prefix = "";
    $thumb_suffix = "";
    $file_prefix = "";
    $file_suffix = "";
    $append_date_stamp = "1";
    $date_stamp=($append_date_stamp=="1")?date(time()):"";
    $haulted = false;
    $upload_folder="uploads/";
    //Check for restrictions
    //Check if upload folder exists
    if(!file_exists($upload_folder)){die("Upload folder doesn't exist");}
    if(!is_writable($upload_folder)){die("Upload folder is not writable");}
    if($make_thumbs == "yes" && !file_exists($thumbs_dir)){die("Thumbnails folder doesn't exist");}
    if($make_thumbs == "yes" && !is_writable($thumbs_dir)){die("Thumbnails folder is not writable");}
    foreach($_FILES as $files => $_file){
        //Check if it's not empty
        if($_file['name']!=""){
            $pathinfo = pathinfo($_file['name']);
            //If allowed extension or no extension restriction
            if(!in_array(strtolower($pathinfo['extension']),$allowed_extensions) && $allowed_ext_string!=""){
                die(strtoupper($pathinfo['extension'])." files are not allowed.
                <br>No files have been uploaded.");
            }
            if($_file['size']>$allowed_size*1048576 && $allowed_size!=0){
                die("The file size of ".basename($_file['name'])." is ".round($_file['size']/1048576,2)."MB,
                which is larger than allowed ".$allowed_size."MB.<br>No files have been uploaded.");
            }       
        }
    }
    //All checks passed, attempt to upload
    foreach($_FILES as $files => $_file){
        //Check if it's not empty
        if($_file['name']!=""){
            $pathinfo = pathinfo($_file['name']);
            $file_name_array = explode(".", basename($_file['name']));
            $filename = $file_name_array[count($file_name_array)-2];
            $target = $upload_folder;
            $file_uploaded = false;
            $target = $target."/".$file_prefix.$filename.$file_suffix.$date_stamp.".".$pathinfo['extension'];
            //if image
            if(strtolower($pathinfo['extension'])=="jpeg" || strtolower($pathinfo['extension'])=="jpg"){
                //if needs resizing or a thumbnail
                if(($resize_image == "yes" && ($resize_width!="" || $resize_height!="")) || ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!=""))){
                    $src = imagecreatefromjpeg($_file['tmp_name']);
                    list($width,$height)=getimagesize($_file['tmp_name']);
                    //if needs thumbnail
                    if ($make_thumbs == "yes" && ($thumb_width!="" || $thumb_height!="")){
                        $thumb_newwidth=($thumb_width!=0)?$thumb_width:(($width/$height)*$thumb_height);
                        $thumb_newheight=($thumb_height!=0)?$thumb_height:(($height/$width)*$thumb_width);
                        $tmp=imagecreatetruecolor($thumb_newwidth,$thumb_newheight);
                        imagecopyresampled($tmp,$src,0,0,0,0,$thumb_newwidth,$thumb_newheight,$width,$height);
                        $thumb_name=$thumb_prefix.$filename.$thumb_suffix.$date_stamp.".".$pathinfo['extension'];
                        if(imagejpeg($tmp,$thumbs_dir."/".$thumb_name,100)){
                            $upload_status=$upload_status."Thumbnail for ".basename($_file['name'])." was created successfully.<br>";
                        }else{
                            die($upload_status."There was a problem creating a thumbnail for ". basename($_file['name']).".
                            Upload was interrupted.<br>");
                        }
                    }
                    //if needs resizing
                    if($resize_image == "yes" && ($resize_width!="" || $resize_height!="")){
                        $newwidth=($resize_width!=0)?$resize_width:(($width/$height)*$resize_height);
                        $newheight=($resize_height!=0)?$resize_height:(($height/$width)*$resize_width);
                        $tmp=imagecreatetruecolor($newwidth,$newheight);
                        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); 
                        if(imagejpeg($tmp,$target,100)){
                            $upload_status=$upload_status.basename($_file['name'])." was successfully resized.<br>";
                            $file_uploaded=true;
                        }else{
                            die($upload_status.basename($_file['name'])." could not be resized. Upload was interrupted.<br>");
                        }
                    }
                }
            }
            if(!$file_uploaded){
                if(move_uploaded_file($_file['tmp_name'], $target)){
                    $upload_status=$upload_status.basename($_file['name'])." was uploaded successfully.<br>";
                }else{
                    $haulted=true;
                }
            }
            //Cleanup
            if(isset($src)){imagedestroy($src);unset($src);}
            if(isset($tmp)){imagedestroy($tmp);unset($tmp);}
            if($haulted){die($upload_status."There was a problem uploading ". basename($_file['name']).".
                        Error: ".$upload_error_codes[basename($_file['error'])].". Upload was interrupted.<br>");}
        }
    }
    if($success_page!="" && $upload_status!=""){
        header("Location: ".$success_page);
    }
}
?>
php upload
1个回答
0
投票

我终于找到了答案。这是上传图像和pdf文件的代码。再次谢谢你。

// Script to upload photo
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $filename = time(). '_' . $_FILES["photo"]["name"]; //$_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

        // Verify file size - 2MB maximum
        $maxsize = 2 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("uploads/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["photo"]["tmp_name"], "uploads/" . $filename);
                echo "Your file was uploaded successfully.";
            } 
        } else{
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else{
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
?>
<?php
// Script to upload fichier1
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["fichier1"]) && $_FILES["fichier1"]["error"] == 0){
        $allowed = array("pdf" => "application/pdf");
        $filename = $filename = time(). '_' . $_FILES["fichier1"]["name"]; //$_FILES["photo"]["name"];
        $filetype = $_FILES["fichier1"]["type"];
        $filesize = $_FILES["fichier1"]["size"];

        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

        // Verify file size - 2MB maximum
        $maxsize = 2097152;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("uploads/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["fichier1"]["tmp_name"], "uploads/" . $filename);
                echo "Your file was uploaded successfully.";
            } 
        } else{
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else{
        echo "Error: " . $_FILES["fichier1"]["error"];
    }
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.