0

Hi

I had an field to upload pdf's only, which worked well. I want to add the option to add docs as well as pdf's and now it is not working:

if (!empty($_FILES['pdf_main']['name']) && ($_FILES['pdf_main']['type']!="application/pdf" || $_FILES['pdf_main']['type']!=             "application/msword")){
        echo '<p class="white">Please check the certificate uploaded. It should be a PDF or Word Document.<br /></p>';
        $found_error = "True";
    }

If I only have one or the other file type, then it works. Can anyone see where I'm going wrong?

Many thanks

3
Contributors
3
Replies
28
Views
3 Years
Discussion Span
Last Post by cereal
0

Hi!

Try to print the mime type received by the $_FILES array. Sometimes the .doc files are not correctly detected. So try:

print_r($_FILES['pdf_main']['type']);

You can also use the Finfo library to check the mime:

$mimes = array(
    'application/msword',
    'application/pdf'
);
$finfo = new Finfo(FILEINFO_MIME_TYPE);

if( ! empty($_FILES['pdf_main']['name']) && ! in_array($finfo->file($_FILES['pdf_main']['type']), $mimes))
{
    # error
}

Important: check with different browsers, because the mime type is sent to the $_FILES array from the client, so if the detection is wrong (or altered) on the client side, you will get an unexpected result. For this reason the Finfo approach is safer: because you effectively check the mime type. In some cases neither this is completely safe. And consider using an antivirus against the doc files, since these can contain infected macros.

Docs:

0

What about checking the extention of the file being uploaded?

Like so:

$file = $_FILES['upload_file']['name'];

$allowed = array('.pdf','.docx','.doc');

$ext = substr($file, strpos($file, '.'), strlen($file)-1);

if(!in_array($ext, $allowed)){
    echo 'File type not allowed';
}else{

    //Run your code here!

}
0

That is good to make sure there is no double extension, but I can still include javascript in the file, for example I create a text file and save it as a.pdf with this contents:

<script>alert('hello');</script>

Then I upload it and this is what is received by the server:

File name is: a.pdf
Array
(
    [pdf_main] => Array
        (
            [name] => a.pdf
            [type] => application/pdf
            [tmp_name] => /tmp/phpNrA2Xg
            [error] => 0
            [size] => 25
        )

)

Now, as you see the mime type is completely wrong as this is a text file, and if you open the file from the server the script will be executed. In case of document files it's important to check the mime, in case of images it's important to check the mime and to strip the comment blocks, because those can be used as containers for PHP code.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.