Embed Images into your PHP Code
While troubleshooting a Wordpress plugin earlier today I discovered a neat little trick with PHP. This particular Wordpress plugin (Brians Threaded Comments) has several tiny images it uses. Rather than distributing the images as seperate files, the author has written them directly into his script! How’s he do it?
Basically, the tiny images have been base64 encoded. The resulting string is put into a PHP variable, which when the script is called with a certain parameter, gets decoded and shot out as an image! Pretty neat!
As an example, I’ll use this image:
A tiny little garbage can icon I use a lot in admin interfaces.
First, we need to encode the image somehow. To do this you could either write a quick little PHP script or use the ‘base64′ utility (linux/bsd).
echo base64_encode("delete.gif");
When base64 encoded, the image turns into a long string that looks like R0lGODlhDwAPAMQAABwcHOLi4oeHh0JCQr6+vmZmZjMzM5mZmf///0pKSszMzCkpKWZmZjo6Oqampvf391lZWZmZmdXV1SAgIHBwcMXFxaurq4qKigAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAQUAP8ALAAAAAAPAA8AAAVjICKOZGkaxmKKaTM1cDMs6jgoUlAdh3BQNdFsARgYGkdAo2RASHYXS6HJRBwIFMeisCypDorCoQGhkr7hg4F7QjgUFDXFPFoeKhDHZNoGxxsFAyYDDzgXPHwlSDRGAxN0KyshADs=
Now here’s a sample of how to put this into action:
if(isset($_GET['image']) && $_GET['image'] == "delete.gif") { header("content-type: image/png"); echo base64_decode("R0lGODlhDwAPAMQAABwcHOLi4oeHh0JCQr6+vmZmZjMzM5mZmf///0pKSszMzCkpKWZmZjo6Oqampvf391lZWZmZmdXV1SAgIHBwcMXFxaurq4qKigAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAQUAP8ALAAAAAAPAA8AAAVjICKOZGkaxmKKaTM1cDMs6jgoUlAdh3BQNdFsARgYGkdAo2RASHYXS6HJRBwIFMeisCypDorCoQGhkr7hg4F7QjgUFDXFPFoeKhDHZNoGxxsFAyYDDzgXPHwlSDRGAxN0KyshADs="); exit; }
To make use of the image in your script, you’d do something like
<img src="?image=delete.gif" alt="" />
And thats it! Easy eh? I’m sure this is an old trick, but one I haven’t seen before. Definitely handy for bundling those little icons and small images directly into your code!

[...] Embed Images into your PHP Code By fdask While troubleshooting a Wordpress plugin earlier today I discovered a neat little trick with PHP. This particular Wordpress plugin (Brians Threaded Comments) has several tiny images it uses. Rather than distributing the images as … fdask on tech – http://blog.ffff.ca [...]
PHP Coding School » Blog Archive » php code [2008-09-27 18:41:21]
27 Sep 08 at 2:54 pm edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>
I wanted to review you on blogexplosion but I just joined and couldn’t comment till mine is approved. Just wanted to say really great information!
Avenuegirl
29 Sep 08 at 10:27 am edit_comment_link(__('Edit', 'sandbox'), ' ', ''); ?>