How to check if it is normal string or binary string in PHP?
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.
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()