- URL: https://www.laruence.com/en/2012/08/30/2731.html
- Please include attribution when republishing.
It all comes from a recent Feature Request: #62961
Back in PHP 5.2.0, the Data URL Scheme (RFC:2397) has already been supported by PHP's Stream wrapper.
Basically, nearly all the file-operation APIs have been migrated to the PHP stream layer, so the vast majority of file-operation APIs support Data URLs.
This post is just a reminder to everyone: when some API needs its target to be a file, we can actually use a Data URL to let it accept a string of file content instead.
For example, in #62961, someone requested that PHP provide an exif_imagetypefromstring API, because the current exif_imagetype API only accepts a filename, while the reporter already has the file content in memory and doesn't want to have to write it to a temporary file just to call exif_imagetype.
<?php
//we already have $bindata
$tmpfile = tempnam('/tmp', 'upload');
file_put_contents($tmpfile, $bin_data);
$extension = image_type_to_extension(exif_imagetype($tmpfile));
unlink($tmpfile);
So, in this situation, we can use a Data URL:
<?php
//we already have $bindata
$base64_data = base64_encode($bin_data);
$extension =
image_type_to_extension(exif_imagetype("data://image/;base64," . $base64_data ));
Also, Data URLs have another quite common use case, like the image below (you can check the source code):
Basically, mainstream browsers now all support this kind of approach, which can save one extra client request for the image.
Finally, this post was written purely to pad the numbers. If you didn't know about this before, please accept it; if you already knew, please ignore it, hehe.
Be First to Comment