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
Warning: File_Get_Contents: Failed to Open Stream: Redirection Limit Reached, Aborting
How to Update Timezonedb in PHP (Updating Timezones Info)
Setting a Cookie in an Ajax Request
Unserialize PHP Data in Python
Curl Import Character Encoding Problem
Comparing Floats - Same Number, But Does Not Equal
PHP Sort($Array) Returning 1 Instead of Sorted Array
Laravel 5.1 Date_Format Validation Allow Two Formats
How to Check Whether Suhosin Is Installed
How to Iterate by Row Through a MySQL Query in PHP
Laravel Change Connection Dynamically
Make Text Between Asterisks Bold
What Is the Best PHP Dom 2 Array Function
Fatal Error: Uncaught Argumentcounterror: Too Few Arguments to Function