2

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);
}
Jonah Katz
  • 5,230
  • 16
  • 67
  • 90
  • How is your question related to phpmailer? Isn't the question how to validate a filetype with PHP? – hakre Aug 08 '11 at 17:29
  • @hakre Well I need to validate before using a phpmailer function AddAttachment.. – Jonah Katz Aug 08 '11 at 17:31
  • There was a similar question some time ago, maybe it's helpful: [phpMailer attachment](http://stackoverflow.com/questions/6322610/phpmailer-attachment/6322645). – hakre Aug 08 '11 at 17:41

1 Answers1

2

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.");
    }
}
Mike
  • 23,542
  • 14
  • 76
  • 87
  • And then how do i add a 'quit and error message' sorta thing to the else statement? (New to php..) – Jonah Katz Aug 08 '11 at 17:30
  • is it `else { die("File type not supported. Only PDF or DOC"); }` ? – Jonah Katz Aug 08 '11 at 17:32
  • Yes, I've updated my answer to reflect this. However you may not want to abruptly quit like that. Generally it is better to throw an exception and then handle it. – Mike Aug 08 '11 at 17:35
  • Actually I just discovered a slight problem.. Your if is located outside the foreach statement, so no matter what it reverts to the else and die – Jonah Katz Aug 08 '11 at 17:46
  • I've added a `foreach()` statement for you. There is no need to do `array_keys()` if you're not using it. `$_FILES` is already an array. – Mike Aug 08 '11 at 17:53
  • Nice. Thanks for the followup – Jonah Katz Aug 08 '11 at 17:55