How to determine if a file is text using PHP?

I am creating a search engine for our giant PHP codebase.

Given the path to the file, how can I determine with a certain degree of certainty whether the file is a text file or some other type? I would prefer not to resort to file extensions (for example, substr($filename, -3) or something stupid), since this is a Linux-based file system, so it all depends on the file extensions.

I am using RecursiveDirectoryIterator, so I have these methods too.

+4
source share
4 answers

Try the finfo_file() function.

Here's a blog describing its use: Finding a smart file using PHP

+10
source
 if (mime_content_type($path) == "text/plain") { echo "I'm a text file"; } 
+1
source

You can call the file utility:

 echo `file '$file'`; 

Returns things like:

 $ file test.out test.out: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped $ file test.cpp test.cpp: ASCII C program text $ file test.txt test.txt: ASCII text $ file test.php test.php: PHP  text 
0
source

Try using: string mime_content_type ( string $filename )

Hope this will be helpful.

William Choi

0
source

All Articles