Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

Possible Duplicate:
How to Check if File is ASCII or Binary in PHP

I have function which accepts either the name of the file of an image (i.e. normal string) or it can directly accept the image bytes as binary string. As returned by file_get_contents.

How can I differentiate between the two?

like image 526
AppleGrew Avatar asked Aug 22 '11 10:08

AppleGrew


2 Answers

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()
like image 183
Arnaud Le Blanc Avatar answered Oct 06 '22 17:10

Arnaud Le Blanc


In PHP all strings are binary (as of current PHP 5.3), so there is no way to differ. So you can not differentiate if the argument is binary data or a filename technically (a string or a string).

You can however create a second function that deals with files which is re-using the function that deals with the image data. So the name of the function makes clear which parameter it expects.


In case you need to decide based on the type passed as parameter to the function, you must add context to the data. One way would be to make parameters of a certain type:

abstract class TypedString
{
    private $string;
    public final function __construct($string)
    {
        $this->string = (string) $string;
    }
    public final function __toString()
    {
        return $this->string;
    }
}

class FilenameString extends TypedString {}

class ImageDataString extends TypedString {}


function my_image_load(TypedString $string)
{
    if ($string instanceof FilenameString)
    {
        $image = my_image_load_file($string);
    }
    elseif ($string instanceof ImageDataString)
    {
        $image = my_image_load_data($string);
    }
    else
    {
         throw new Exception('Invalid Input');
    }
    # continue loading the image if needed
}
function my_image_load_file($filename)
{
    # load the image from file and return it
}
function my_image_load_data($data)
{
    # load the image from data and return it
}

However I think it's easier to deal with proper named functions instead, otherwise you're making things needlessly complex if you're using classes for type differentiation only.

like image 35
hakre Avatar answered Oct 06 '22 17:10

hakre