在phpmailer中添加文件类型验证?

时间:2011-08-08 17:23:17

标签: php file-upload validation phpmailer

我有一个phpmailer,通过循环文件输入字段中的文件数组来附加文件。我怎样才能使它允许使用onl PDF或DOC。如果尝试了其他操作,脚本会停止并发出错误:“不支持文件类型。只有PDF或DOC。”

有什么建议吗?这是我目前的剧本;

foreach(array_keys($_FILES['files']['name']) as $key) {
        $source = $_FILES['files']['tmp_name'][$key];
        $filename = $_FILES['files']['name'][$key];
        $mail->AddAttachment($source, $filename);
}

1 个答案:

答案 0 :(得分:2)

您需要查看$ _FILES ['files'] ['type']并确保它与您想要的mime类型相匹配。

foreach ($_FILES as $file) {
    if ($file['files']['type'] == 'application/msword' 
        || $file['files']['type'] == 'application/pdf'
    ) { 
        $source = $file['files']['tmp_name'][$key];
        $filename = $file['files']['name'][$key];
        $mail->AddAttachment($source, $filename);
    }
    else {
        die("You may only upload PDF and Microsoft Word documents through this form.");
    }
}