tags:

views:

818

answers:

2

Is there a quick, simple way to check if a file is ASCII or binary with PHP?

DUPLICATE http://stackoverflow.com/questions/620993/determining-binary-text-file-type

+1  A: 

Since ASCII is just an encoding for text, with binary representation, not really. You could check that all bytes are less than 128, but even this wouldn't guarantee that it was intended to be decoded as ASCII. For all you know it's some crazy image format, or an entirely different text encoding that also has no use of all eight bits. It might suffice for your use, though. If you just want to check if a file is valid ASCII, even if it's not a "text file", it will definitely suffice.

Devin Jeanpierre
A: 

This only works for PHP>=5.3.0, and isn't 100% reliable, but hey, it's pretty darn close.

// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME);

//check to see if the mime-type starts with 'text'
return substr(finfo_file($finfo, $filename), 4) == 'text';

http://us.php.net/manual/en/ref.fileinfo.php

davethegr8