Skip to content

Instantly share code, notes, and snippets.

@Radon8472
Last active February 7, 2021 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Radon8472/23dc22e9af56977e5f639a18385cc4ae to your computer and use it in GitHub Desktop.
Save Radon8472/23dc22e9af56977e5f639a18385cc4ae to your computer and use it in GitHub Desktop.
Helper functions
<?php
/**
* creates a data url
*
* @version: 1.0
*
* @param string $data Data string that should be encoded
* @param string [$mime] Mime Type of the data (optional)
* @param string [$charset] charset of data (only used when it is not base64) (optional)
* @param bool [$base64] Should data be decoded as base64 - If NULL, base64 is detected by the content-type
*
* @return String Data uri
*
*/
function data_uri($data, $mime = "", $charset = "", $base64 = null)
{
// skip minetype for this case, because "text/plain" is default
if($mime == "text/plain" || trim($mime) == "") $mime = "";
// Charset is US_ASCII by default, so wie can omit this here
$charset = ($charset == "US-ASCII" || $charset == "")
? ""
: ";charset=" . $charset;
// if $base64 is not set, choose by content-type
if(is_null($base64))
{
if(stripos($mime, "text/") === 0)
$base64 = false;
else {
switch (trim($mime)) {
// list of all non "text/*" types that should no be base64 encoded
case "image/svg+xml":
{
$base64 = false;
break;
}
default:
$base64 = true;
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment