虽然在条件中指定了filetype,但PHP文件上载不起作用

时间:2015-12-05 05:33:49

标签: php file-upload

当我尝试上传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>

自由签证评估外形过程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();
    }
}

2 个答案:

答案 0 :(得分:1)

实际上,$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);

答案 1 :(得分:1)

代码中的两个错误

1)您是MIME类型

的匹配文件扩展名
from shutil import copytree
import mock  # import unittest.mock as mock   in Python 3.x

with mock.patch('os.makedirs'):
    copytree('PlaceB', 'PlaceA')

2)您正在将目标文件夹传递到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") {

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

中添加了enctype="multipart/form-data">