0

Currently in my code the extension of the files is checked before it is uploaded to the server. I need to check the content of the files too before uploading it to server. I have used the following code


    $FileName = $_FILES[$imageInput]['name'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mtype = finfo_file($finfo, $FileName);

$mtype is correctly identified for all image type like .png , .jpg but it doesn't recognised .sh files. How can I check this using php? Some one please help.

2 Answers2

0

You can block various files to be executed via .htaccess. For example you can place this

<FilesMatch "\.(sh|cgi.+)$">
    ForceType text/plain
</FilesMatch>

This will ensure files in the folder will return as text/plain

If you want you can detect mime type as you detect for images. Mime type for .sh is

application/x-sh
application/x-csh
text/x-shellscript
S.I.
  • 3,250
  • 12
  • 48
  • 77
0

In this case, you can try cross-validate between mime type and extension by taking the extension through the following scripts:

$fileExtension= end(explode(".", $_FILES["uploadedFile"]["name"]));

or

$fileName = ($_FILES['uploadedFile']['name']);

$fileExtension = pathinfo($fileName , PATHINFO_EXTENSION);

And later, apply something like:

$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $fileExtension = array_search(
    $finfo->file($_FILES['uploadedFile']['tmp_name']),
    array(
        //'sh' => 'text/x-shellscript', //not allowed
        'docx'  => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'rtf' => 'text/rtf',
        'odt' => 'application/vnd.oasis.opendocument.text',
        'txt' => 'text/plain',
        'pdf' => 'application/pdf',
    ),
    true
)) {
     $error .= "<br> The allowed file format file are: \"doc\", \"docx\", \"rtf\", \"odt\", \"txt\", \"pdf\"' ";
}

I had a problem similar to this, but in my case the file was .rtf type.

The FILEINFO_MIME_TYPE function apparently can not capture any type of file extension, this can lead to some validation errors.

Some examples: The default mime type for .rtf files is application/rtf, but the FILEINFO_MIME_TYPE function displays text/rtf.

I wasted a lot of time trying to solve this bug as I described it here:

In the case of .sh files I noticed that the FILEINFO_MIME_TYPE function can not capture the extension, it returns me a null value

saudade
  • 1
  • 3