Stephen Thompson February 2016

multiple attachments are sent with phpmailer, I need to save to server only PDF's

I have an issue with one page of a rather large application. The page has a form that attaches files from the user and emails them with PHPMailer. I now need to add the ability to save only those attachments that are PDF's. I have included the section that needs tweeking. the new section in between the lines of asterisks.

//Handle the files
$total = count($_FILES['uploadfile']['tmp_name']);
    for ($i = 0; $i < $total; $i++) {
    $name = $_FILES['uploadfile']['name'][$i];
    $path = $_FILES['uploadfile']['tmp_name'][$i];
    $type = $_FILES['uploadfile']['type'][$i];
    $mail->AddAttachment($path,$name);
 //*************************************************************************************
// NEW PDF CHECK HERE
$ext = pathinfo($path, PATHINFO_EXTENSION);

if ($ext == '.pdf'){
    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'][$i], "path/to/file/{$_FILES['uploadfile']['name']}")){
            $pdfquery = "INSERT INTO reports (case_id, user_id, filename, upload_date, dept_id) VALUES ('$case_id', '$user', '{$_FILES['uploadfile']['name']}', CURDATE(), '$dept_id')";
            $pdfresult = mysqli_query($dbc, $pdfquery) or trigger_error("Query: $pdfquery\n<br>MySQL Error: " . mysqli_error($dbc));

            if (mysqli_affected_rows($dbc) == 1){
                echo 'PDF Case Report Saved.<br><br>';
            } else {
                echo 'report failed to save to database.';

            }//END affected rows
     }  // END move report.
} // END $ext check.

//************************************************************************************* 
    } // END for loop.

Answers


Lajos Arpad February 2016

You need to simply check mime type, not the extention (.pdf), since one can upload a PHP file named evil.pdf to your server or someone might upload a pdf having a different extention. I show you just the part relevant to the question.

$total = count($_FILES['uploadfile']['tmp_name']);
for ($i = 0; $i < $total; $i++) {
    //Attach the file anyway
    $name = $_FILES['uploadfile']['name'][$i];
    $path = $_FILES['uploadfile']['tmp_name'][$i];
    $type = $_FILES['uploadfile']['type'][$i];
    $mail->AddAttachment($path,$name);
    if (finfo_file(finfo_open(FILEINFO_MIME_TYPE), $_FILES['file']['tmp_name']) !== 'application/pdf') {
        //file does not have the expected mime type, possibly this is a hack
        //attempt, therefore we ignore the file
        continue;
    }
    //If the program reaches this point, then the file is PDF
}

Post Status

Asked in February 2016
Viewed 3,616 times
Voted 6
Answered 1 times

Search




Leave an answer