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

base64, php

Solution

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.

Problem

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)) {} ```

Original source

Related problems