简体   繁体   中英

How to check file type

I'll check on server side (PHP) if a file is a real . txt or not. At the moment I've wrote :

if(substr($_FILES['tracklistFile']['name'], -3)=='txt')

but I think that its not the best solution! How can I check it?

To reliably get the file extension, use this:

pathinfo($_FILES['tracklistFile']['name'], PATHINFO_EXTENSION);

That will, however, only give you just that - the extension part of the filename. It says nothing about the actual type of the file.

If the file is a local file on your server (as opposed to being uploaded), you could call the file command available on most Unix-based operating systems.

Uhm...for example if a user call picture.jpg as picture.txt this check will fail, and my script can create many errors :) Won't be under control :)

Okay, but by what criteria would you tell the invalid JPG apart from a valid text file? A text file could theoretically contain anything . It has no defined format whatsoever, it just consists of a number of completely arbitrary bytes.

MIME type detection as suggested by @Sardine will have the same problem; however, it will be able to detect many file types that are not a text file, so you can reject those. Still, it will not be 100% reliable.

You will need to think of some rules that allow you to recognize a text file, depending on what your script is going do with them.

If it's just for the sake of finding out whether it's a text file, I would consider not doing any checks at all. You just need to make sure it gets treated as a text file in every step of your application (ie if it contains PHP, JavaScript or HTML code, it won't be executed).

If possible, you can check for the mime type of the file which should be

text/plain

This is unfortunately a tricky task in PHP. If you are using PHP4, you can use the following:

$mtype = mime_content_type($file_path);

If you have PHP >= 5.3.0 & PECL fileinfo >= 0.1.0, you can use something like:

$finfo = finfo_open(FILEINFO_MIME);
$mtype = finfo_file($finfo, $file_path);
finfo_close($finfo);

If neither of these work, I would recommend at least making sure it isn't something like a picture using methods discussed in other answers. Without being able to use these functions, you can only do the unfortunate method of checking the file name to determine the file type, which is not at all reliable.

Sources:

http://www.php.net/manual/en/book.fileinfo.php

http://forums.digitalpoint.com/showthread.php?t=522166

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM