Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking filetypes when uploading, and browser dependency issues

Tags:

mime-types

php

I'm building a php file uploader and I've some issues with security. For example I don't want to allow ".php" file uploads. As I know the only way to check the file type is with $_FILES['file']['type'] and the value of it is browser dependent.

I check with multiple browsers and found that when selecting a regular .php file different browsers return these values:

firefox: application/x-download
chrome: text/plain
safari: text/plain
IE: text/plain
opera: application/octet-stream

I've also tried the same experiment with the regular .txt files and all browses return text/plain as the mime type.

So here's the problem, If I want to allow the .txt file upload what should I do to prevent .php file uploads?

like image 367
Yasser Souri Avatar asked May 16 '26 14:05

Yasser Souri


2 Answers

Don’t rely on the information the client sends. Even the media type the client sends can be forged.

If you don’t want to allow PHP files, just don’t allow files with the file extension .php or change it to .txt:

if (strtolower(strrchr($_FILES['file']['name'], '.')) == '.php') {
    // has file extension .php
}
like image 184
Gumbo Avatar answered May 19 '26 05:05

Gumbo


Use the following function:

function Mime($path)
{
    $result = false;

    if (is_file($path) === true)
    {
        if (function_exists('finfo_open') === true)
        {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            if (is_resource($finfo) === true)
            {
                $result = finfo_file($finfo, $path);
            }

            finfo_close($finfo);
        }

        else if (function_exists('mime_content_type') === true)
        {
            $result = preg_replace('~^(.+);.*$~', '$1', mime_content_type($path));
        }

        else if (function_exists('exif_imagetype') === true)
        {
            $result = image_type_to_mime_type(exif_imagetype($path));
        }
    }

    return $result;
}

This will return the proper mime type of any file.

like image 25
Alix Axel Avatar answered May 19 '26 05:05

Alix Axel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!