Data URI base64 PHP function


/ Published in: PHP
Save to your folder(s)

**Example of use:**

echo base64DataUri('/var/www/html/background.png');

*or*

echo base64DataUri('http://static.php.net/www.php.net/images/php.gif');


Copy this code and paste it in your HTML
  1. /**
  2.  * Data URI base64 PHP function.
  3.  *
  4.  * @author Pierre-Henry Soria <[email protected]>
  5.  * @copyright (c) 2012-2013, Pierre-Henry Soria. All Rights Reserved.
  6.  * @license Lesser General Public License (LGPL) <http://www.gnu.org/copyleft/lesser.html>
  7.  * @param string $sFile The path of your file to encode.
  8.  * @return string The encoded data in base64.
  9.  */
  10. function base64DataUri($sFile)
  11. {
  12.  
  13. // Switch to right MIME-type
  14. $sExt = strtolower(substr(strrchr($sFile, '.'), 1));
  15.  
  16. switch($sExt)
  17. {
  18. case 'gif':
  19. case 'jpg':
  20. case 'png':
  21. $sMimeType = 'image/'. $sExt;
  22. break;
  23.  
  24. case 'ico':
  25. $sMimeType = 'image/x-icon';
  26. break;
  27.  
  28. case 'eot':
  29. $sMimeType = 'application/vnd.ms-fontobject';
  30. break;
  31.  
  32. case 'otf':
  33. case 'ttf':
  34. case 'woff':
  35. $sMimeType = 'application/octet-stream';
  36. break;
  37.  
  38. default:
  39. exit('Invalid extension file!');
  40. }
  41.  
  42. $sBase64 = base64_encode(file_get_contents($sFile));
  43. return "data:$sMimeType;base64,$sBase64";
  44. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.