I am creating a lightweight, single-file database administration tool and I would like to bundle some small icons with it. What is the best way to embed images in a HTML/PHP
Something like this?
http://www.sveinbjorn.org/dataurls_css
A solution to embed an image directly in an HTML page would be to use the data URI scheme
For instance, you could use some portion of HTML that looks like this :
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
There are other solutions on the wikipedia page I linked to :
But note those solutions will not work on all browsers -- up to you to decide whether this is acceptable or not, in your specific situation.
Edit : to answer the question you asked about "how to generate Data URL's properly with PHP", take a look a bit lower in the wikipedia page about the Data URI scheme, which gives this portion of code (quoting) :
function data_uri($file, $mime)
{
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
?>
<img src="<?php echo data_uri('elephant.png','image/png'); ?>" alt="An elephant" />
For one PHP server side script try a base64 encode of the graphic and use a simple controller-style logic:
<?
/* store image mime-type and data in script use base64 */
$images = array('photo.png' => array('mimetype' => 'image/png',
'data' => '...'));
/* use request path, e.g. index.php/photo.png */
$action = substr($_SERVER['PATH_INFO'], 1);
switch($action) {
case (preg_match('/\.png$/', $action)?$action:!$action):
header("Content-Type: {$images[$action]['mimetype']}");
/* use expires to limit re-requests on navigation */
$expires = gmdate('D, d M Y H:i:s \G\M\T', filetime(__FILE__) + 365*24*60*60);
header("Expires: {$expires}");
$data = base64_decode($images[$action]['data']);
header('Content-Length: ' . strlen($data));
echo $data;
break;
...
}
?>