I have to create a PHP that will return an image stream of one transparent dot (PNG or GIF)
Could you point me to an easy to use solution?
In PHP 5.4 and higher it is possible to use hex2bin, which is roughly two times faster than base64_decode (tested with the blank GIF file below). The code to output images would be:
Transparent 1x1 PNG:
header('Content-Type: image/png');
die(hex2bin('89504e470d0a1a0a0000000d494844520000000100000001010300000025db56ca00000003504c5445000000a77a3dda0000000174524e530040e6d8660000000a4944415408d76360000000020001e221bc330000000049454e44ae426082'));
Transparent 1x1 GIF:
header('Content-Type: image/gif');
die(hex2bin('47494638396101000100900000ff000000000021f90405100000002c00000000010001000002020401003b'));
You can easily convert base64 encoded data into hexadecimal:
echo bin2hex(base64_decode($data));
Or a file:
echo bin2hex(base64_decode(file_get_contents($filename)));
However, using the native PHP escape method suggested by @Lukas Liesis is the fastest, about 12.5 times faster than base64_decode, according to my benchmark. And it would work with virtually any version of PHP. Here are the code snippets:
Transparent 1x1 PNG:
header('Content-Type: image/png');
die("\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x01\x00\x00\x00\x01\x01\x03\x00\x00\x00\x25\xdb\x56\xca\x00\x00\x00\x03\x50\x4c\x54\x45\x00\x00\x00\xa7\x7a\x3d\xda\x00\x00\x00\x01\x74\x52\x4e\x53\x00\x40\xe6\xd8\x66\x00\x00\x00\x0a\x49\x44\x41\x54\x08\xd7\x63\x60\x00\x00\x00\x02\x00\x01\xe2\x21\xbc\x33\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82");
Transparent 1x1 GIF:
header('Content-Type: image/gif');
die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x90\x00\x00\xff\x00\x00\x00\x00\x00\x21\xf9\x04\x05\x10\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x04\x01\x00\x3b");
Creating such a string is easy with regular expressions (as it's done once, it doesn't have to work fast):
echo preg_replace('/../','\\x\0',bin2hex($data));
Or from a file:
echo preg_replace('/../','\\x\0',bin2hex(file_get_contents($filename)));