How to Check If File Is Ascii or Binary in PHP

How to Check if File is ASCII or Binary in PHP

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

How to check if it is normal string or binary string in PHP?

You could check if the input is composed only of printable characters. You can do that with ctype_print() if you're only using ASCII characters 32 thru 126 and have zero expectations of Unicode characters:

if (ctype_print($filename)) { // this is most probably not an image

You could also check if the argument is a valid image, or if a file with that name exists.

However it would be better and more reliable to create two separate functions:

  • a load_image_from_string() that always takes an image as parameter
  • and a load_image_from_file() that would read the file and call load_image_from_string()

PHP - Validate that a file only contains ASCII

You can use:

  • mb_detect_encoding():

    mb_detect_encoding(file_get_contents($filename), 'ASCII', true) === false
  • A regular expression:

    preg_match('/^[\x20-\x7e]*$/', file_get_contents($filename)) > 0

Check if a file is binary or ASCII with Node.js?

Thanks to the comments on this question by David Schwartz, I created istextorbinary to solve this problem.

Detect if string is binary

This will have to do.

function isBinary($str) {
return preg_match('~[^\x20-\x7E\t\r\n]~', $str) > 0;
}


Related Topics



Leave a reply



Submit