Shlomi Atia
Shlomi Atia

Reputation: 105

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

I'm using PHP to upload a file, but I would like to allow only PDF,DOC,DOCX. I found some answers here but none of them helped me.

Thats my code:

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

Upvotes: 0

Views: 411

Answers (2)

ajit
ajit

Reputation: 86

You can use below code to check whether uploaded file is correct or not.

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

Upvotes: 4

Ankit Kumar
Ankit Kumar

Reputation: 180

Use 'Type' to find the the type of File being uploaded. If it is PDf/Mswrod , then continue with your code, else show the user an error that only PDF and Docs are allowed. Btw, Please try uploading the doc and docs, and try to print their type, if their type is something which I have not covered in my "If" condition, then please add them in the existing "If" condition using "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');
}

Upvotes: 2

Related Questions