Add a filetype validation to phpmailer?

2019-07-24 04:45发布

I have a phpmailer that attaches files by looping through an array of files from an file input field. How can i make it so that onl PDF or DOC are allowed. And if something else is attempted, the script stope and gives an error: "File type not supported. Only PDF or DOC."

Any suggestions? Heres my current script;

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

1条回答
Anthone
2楼-- · 2019-07-24 04:59

You need to look at $_FILES['files']['type'] and make sure it matches the mime types you want.

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.");
    }
}
查看更多
登录 后发表回答