【问题标题】:I have this code for uploading files, I would like to allow only PDF, DOC, DOCX我有这个用于上传文件的代码,我想只允许 PDF、DOC、DOCX
【发布时间】:2015-06-18 14:14:53
【问题描述】:

我正在使用 PHP 上传文件,但我想只允许 PDF、DOC、DOCX。 我在这里找到了一些答案,但没有一个对我有帮助。

这是我的代码:

$from = str_replace(array("\r", "\n"), '', $mail); // to prevent email injection
    if ($file) {
        $filename = basename($_FILES['fileupload']['name']);
        $file_size = filesize($file);
        $content = chunk_split(base64_encode(file_get_contents($file))); 
        $uid = md5(uniqid(time()));
        $header = "MIME-Version: 1.0\r\n"
            ."From: {$name}<{$from}>\r\n"
            ."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"
            ."This is a Mime.\r\n\r\n" 
            ."--".$uid."\r\n"
            ."From: {$name}<{$from}>\r\n"
            ."Content-type:text/html; charset=UTF-8\r\n\r\n"
            .$msg1."\r\n\r\n"
            ."--".$uid."\r\n"
            ."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
            ."Content-Transfer-Encoding: base64\r\n"
            ."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
            .$content."\r\n\r\n"
            ."--".$uid."--"; 
        $msg1 = '';
    } else {
        $header  = "MIME-Version: 1.0\r\n";
        $header .= "Content-type: text/html; charset=UTF-8\r\n";
        $header .= "From: <".$mail. ">" ;
    }

【问题讨论】:

标签: php file file-upload


【解决方案1】:

您可以使用以下代码检查上传的文件是否正确。

$FileType = pathinfo($filename,PATHINFO_EXTENSION);
if($FileType != "pdf" && $FileType != "doc" && $FileType != "docx") {
        echo "Sorry, only PDF, DOC, DOCX files are allowed.";
}

【讨论】:

    【解决方案2】:

    使用“类型”查找上传文件的类型。如果是 PDf/Mswrod ,则继续使用您的代码,否则向用户显示仅允许 PDF 和 Docs 的错误。顺便说一句,请尝试上传文档和文档,并尝试打印它们的类型,如果它们的类型是我的“如果”条件中没有涵盖的内容,那么请使用“或”将它们添加到现有的“如果”条件中( ||)。

        if (($_FILES["file"]["type"] == "application/pdf" || $_FILES["file"]["type"] == "application/msword")
    {
    //   If file is Pdf or Doc, process your code
    }
    else
    {
                  $type = $_FILES["file"]["type"];
    
                    echo "Your file type is ".$type." while we only accept PDF and Doc.<br/>";
                    die('Try Again');
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-02
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2023-03-12
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多