ditto
ditto

Reputation: 6277

What is the best method to determine if a value is either a base64 string or an image URL?

I have a value that may be either an image URL or an image Base64 string. What is the best method to determine which is which? If it's an image URL, the image will already reside on my server.

I've tried doing a preg_match but I think running a preg_match on a potentially huge base64 string will be server intense.

EDIT: The two best methods thus far.

// if not base64 URL
if (substr($str, 0, 5) !== 'data:') {}

// if file exists
if (file_exists($str)) {}

Upvotes: 4

Views: 2580

Answers (3)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7880

You can do this with preg_match(). When preg_match doesn't see the d, the code will stop. if it finds a d not followed by an a it will stop and so on. Also this way you're not doing superfluous math and string parsing:

if(!preg_match('!^data\:!',$str) {
  //image
} else {
  //stream
}

You can also use is_file() which will not return true on directories.

// if file exists and is a file and not a directory
if (is_file($str)) {}

Upvotes: 0

Marc B
Marc B

Reputation: 360702

You mean you want to differentiate between

<img src="http://example.com/kittens.jpg" />
and
<img src="data:image/png;base64,...." />

You'd only need to look at the first 5 chars of the src attribute to figure out if it's a data uri, e.g.

if (substr($src, 0, 5) == 'data:')) {
    ... got a data uri ...
}

If it doesn't look like a data uri, then it's safe to assume it's a URL and treat it as such.

Upvotes: 5

Amal Murali
Amal Murali

Reputation: 76656

If those are only two possibilities, you can do something like:

$string = 'xxx';
$part = substr($string, 0, 6); //if an image, it will extract upto http(s):

if(strstr($part, ':')) {
    //image
} else {
    //not an image
}

Explanation: The above code assumes that the input is either a base64 string or an image. If it's an image, it will and should contain the protocol information (including the :). That's not allowed in a base64 encoded string.

Upvotes: 0

Related Questions