Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check if File is ASCII or Binary in PHP

Tags:

php

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

like image 269
davethegr8 Avatar asked Mar 10 '09 23:03

davethegr8


2 Answers

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), 0, 4) == 'text';

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

like image 102
davethegr8 Avatar answered Oct 23 '22 18:10

davethegr8


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.

like image 27
Devin Jeanpierre Avatar answered Oct 23 '22 18:10

Devin Jeanpierre