Image Data URIs with PHP

If you troll page markup like me, you’ve no doubt seen the use of data URI’s within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves a network request for each image, and if you’re the paranoid type, can prevent exposure of directory paths. Since creating data URIs is incredibly easy, let me show you how to do it with PHP.

Start by reading in the image using file_get_contents (or any other PHP method you’d like), then convert the image to base64 using base64_encode:

With the image data in base64 format, the last step is placing that data within the data URI format, including the image’s MIME type. This would make for a good function:

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA