Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a file is text using PHP?

I'm making a search engine for our gigantic PHP codebase.

Given a filepath, how can I determine with some degree of certainty whether a file is a text file, or some other type? I'd prefer not to have to resort to file extensions (like substr($filename, -3) or something silly), as this is a linux based filesystem, so anything goes as far as file extensions are concerned.

I'm using RecursiveDirectoryIterator, so I have those methods available too..

like image 852
Stephen Fuhry Avatar asked Sep 08 '10 17:09

Stephen Fuhry


2 Answers

Try the finfo_file() function.

Here's a blog describing its usage: Smart File Type Detection Using PHP

like image 200
Bill Karwin Avatar answered Sep 27 '22 00:09

Bill Karwin


if (mime_content_type($path) == "text/plain") {
 echo "I'm a text file";
}
like image 24
softcr Avatar answered Sep 23 '22 00:09

softcr