我有这个上传文件的代码,我只想允许 PDF、DOC、DOCX

I have this code for uploading files, I would like to allow only PDF, DOC, DOCX

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

那是我的代码:

$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. ">" ;
    }

使用'Type'查找正在上传的文件类型。如果是 PDf/Mswrod ,则继续您的代码,否则向用户显示仅允许 PDF 和 Docs 的错误。顺便说一句,请尝试上传 doc 和 docs,并尝试打印它们的类型,如果它们的类型是我的 "If" 条件中未涵盖的内容,请将它们添加到现有的 "If" 条件中使用"OR" (||).

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

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

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