Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does php file_info return inode/x-empty for empty text files?

Tags:

php

I am currently working on a class that wraps the finfo_file function.

The following script returns inode/x-empty for all empty text files:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo,'/path/to/text_file.txt');

Tested in the following environments and received the same results.

WAMP
Windows 7
PHP 5.4.27
APACHE 2.2.22

Linux
Ubuntu
PHP 5.5.10
APACHE 2.4.9

My goal is to setup the class so that I can white list file types. If a MIME type of text/plain is white listed, the empty text file would fail since it returns a MIME type of inode/x-empty.

Is this default behavior for the finfo_file function?

like image 570
bjtilley Avatar asked Mar 20 '23 10:03

bjtilley


2 Answers

Yes, because the file extension doesn't define the file type. You can, in example, change the extension of a video file from .mp4 to .txt, and still play the video in a player. Windows does handle file extensions a bit more strictly, but in unix systems the extension is more like a type-hint for users then that it really means something for the system itself (exceptions are there though).

The file info functions look to the contents of a file and try to determine the mime-type from what it finds there.

If you want to white-list text/plain, but also empty text files, you could do something like this, using pathinfo():

if($mime_type == 'inode/x-empty' && pathinfo($file_name, PATHINFO_EXTENSION) == 'txt') {
    // whitelist
}
like image 95
giorgio Avatar answered Mar 22 '23 01:03

giorgio


From the documentation:

Returns a textual description of the contents of the filename argument, or FALSE if an error occurred.

(emphasis mine). As you can see, it's based on the contents, not the name.

like image 32
Barmar Avatar answered Mar 21 '23 23:03

Barmar