尽管条件中指定了文件类型,但PHP文件上载无法工作


PHP file upload not working although filetype is specified in the condition

当我尝试上传word doc(.docx)文件时,它会发出警告消息"对不起,只允许word、txt、rtf或pdf文件。对不起,你的文件没有上传。"尽管在if条件语句中我提到msword是文件类型之一。

<?php
$target_dir = "./blog/wp-content/uploads/resumes";
$target_file = $target_dir . basename($_FILES["uploadCV"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check file size
if ($_FILES["uploadCV"]["size"] > 1024000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" && $imageFileType != "application/msword" && $imageFileType != "application/txt" && $imageFileType != "rtf;application/rtf" && $imageFileType != "application/pdf" && $imageFileType != "rtf;text/richtext" && $imageFileType != "rtf;text/richtext") {
    echo "Sorry, only word, txt, rtf or pdf files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["uploadCV"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["uploadCV"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

HTML代码

<form class="assessment-form-step-3" action="free-visa-assessment-form-process-3.php" method="post" enctype="multipart/form-data">
                    <h2>About your Profession</h2>
                    <div>
                        <input class="assessment-occupation" name="assessment-occupation" data-validation="required" data-validation="length" data-validation-length="min3" type="text" placeholder="Your occupation" data-validation-error-msg="Please enter your occupation">
                    </div>
                    <div>
                        <select class="assessment-highest-qualification" name="assessment-highest-qualification" data-validation="required" data-validation-error-msg="Please select your highest qualification">
                            <option value="">Select your highest level of qualification</option>
                            <option value="PhD">PhD</option>
                            <option value="Masters">Masters</option>
                            <option value="Bachelor">Bachelor</option>
                            <option value="Diploma">Diploma</option>
                            <option value="Certificate">Certificate</option>
                        </select>
                    </div>
                    <div>
                        <select class="assessment-experience" name="assessment-experience" data-validation="required" data-validation-error-msg="Please select appropriate type of visa that you're looking for">
                             <option value="">Select years of work experience</option>
                              <option value="Less than a year">Less than a year</option>
                              <option value="1 year">1 year</option>
                              <option value="2 years">2 years</option>
                              <option value="3 years">3 years</option>
                              <option value="4 years+">4 years+</option>
                        </select>
                    </div>
                    <div>
                       <label for="">Upload your resume (optional)</label>
                        <input type="file" class="uploadCV" name="uploadCV" id="uploadCV" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,.pdf,text/plain,application/rtf">
                    </div>
                    <div>
                        <textarea name="assessment-comments" placeholder="Enter your comments" class="assessment-comments" cols="30" rows="10"></textarea>
                    </div>
                    <button class="full-width green proceed-to-thankyou">Submit &nbsp;&nbsp;&nbsp; <img style="width:22px;" src="img/lock-icon.png" alt=""></button>
                    <p></p>
                </form>

free-visa-assement-form-process-3.php

<?php
session_start();
if (!$_POST['assessment-occupation'] || !$_POST['assessment-highest-qualification'] || !$_POST['assessment-experience']) {
    echo "<p>Please supply all of the data!</p>";
    exit;
}
else {
    require('db-connection.php');
    require('file-upload-script.php');
    try {  
        $stmt = $conn->prepare("UPDATE visa SET job_title= :occupation, Qualifications= :qualification, experience= :experience, file_path= :file_upload, comments= :comments WHERE id= :id");
        // escape variables for security
        $stmt->bindParam(':occupation', $_POST['assessment-occupation']);
        $stmt->bindParam(':qualification', $_POST['assessment-highest-qualification']);
        $stmt->bindParam(':experience', $_POST['assessment-experience']);
        $stmt->bindParam(':file_upload', $target_file);
        $stmt->bindParam(':comments', $_POST['assessment-comments']);
        $stmt->bindParam(':id', $_SESSION["regId"]);
        $stmt->execute();
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

代码中的两个错误

1) 您正在将文件扩展名与MIME类型匹配

if($imageFileType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" && $imageFileType != "application/msword" && $imageFileType != "application/txt" && $imageFileType != "rtf;application/rtf" && $imageFileType != "application/pdf" && $imageFileType != "rtf;text/richtext" && $imageFileType != "rtf;text/richtext") {

2) 您正在将目标文件夹传递到pathinfo()

$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

你必须创建一个扩展数组并匹配你的数组

 $allowed =  array('word', 'txt', 'rtf', 'pdf','docx');
    $ext = pathinfo($_FILES["uploadCV"]["name"], PATHINFO_EXTENSION);//pass file name here
    if(!in_array($ext,$allowed) ) {
        echo "Sorry, only word, txt, rtf or pdf files are allowed.";
        $uploadOk = 0;
    }

确保已在form tag 中添加enctype="multipart/form-data">

实际上,$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);将返回文件的扩展名。所以,如果你想允许txt、word、pdf或rtf文件,试试这个。

  //define an array containing file types
  $allowedFileTypes = array("txt", "pdf", "rtf", "docx", "doc");
  //condition to check
  if(!in_array($imageFileType, $allowedFileTypes ))
  {
      echo "Sorry, only word, txt, rtf or pdf files are allowed.";
      $uploadOk = 0;
  }

编辑

您必须使用此代码获得扩展。

  $imageFileType = pathinfo($_FILES['uploadCV']['name'],PATHINFO_EXTENSION);