Return to Snippet

Revision: 62455
at February 24, 2013 12:02 by phpdev


Updated Code
/**
 * Data URI base64 PHP function.
 * 
 * @author        Pierre-Henry Soria <[email protected]>
 * @copyright     (c) 2012-2013, Pierre-Henry Soria. All Rights Reserved.
 * @license       Lesser General Public License (LGPL) <http://www.gnu.org/copyleft/lesser.html>
 * @param         string $sFile The path of your file to encode.
 * @return        string The encoded data in base64.
 */
function base64DataUri($sFile)
{                   

    // Switch to right MIME-type
    $sExt = strtolower(substr(strrchr($sFile, '.'), 1));
     
    switch($sExt)
    {
		case 'gif':
		case 'jpg':
		case 'png':
			$sMimeType = 'image/'. $sExt;
		break;
		
		case 'ico':
			$sMimeType = 'image/x-icon';
		break;
		
		case 'eot':
			$sMimeType = 'application/vnd.ms-fontobject';
		break;
		
		case 'otf':
		case 'ttf':
		case 'woff':
			$sMimeType = 'application/octet-stream';
		break;
		
		default:
		    exit('Invalid extension file!');
	}

    $sBase64 = base64_encode(file_get_contents($sFile));
    return "data:$sMimeType;base64,$sBase64";
}

Revision: 62454
at February 24, 2013 11:44 by phpdev


Initial Code
/**
 * Data URI base64 PHP function.
 * 
 * @author        Pierre-Henry Soria <[email protected]>
 * @copyright     (c) 2012-2013, Pierre-Henry Soria. All Rights Reserved.
 * @license       Lesser General Public License (LGPL) (http://www.gnu.org/copyleft/lesser.html)
 * @param         string $sFile The path of your file to encode.
 * @return        string The encoded data in base64.
 */
function base64DataUri($sFile)
{                   

    // Switch to right MIME-type
    $sExt = strtolower(substr(strrchr($sFile, '.'), 1));
     
    switch($sExt)
    {
		case 'gif':
		case 'jpg':
		case 'png':
			$sMimeType = 'image/'. $sExt;
		break;
		
		case 'ico':
			$sMimeType = 'image/x-icon';
		break;
		
		case 'eot':
			$sMimeType = 'application/vnd.ms-fontobject';
		break;
		
		case 'otf':
		case 'ttf':
		case 'woff':
			$sMimeType = 'application/octet-stream';
		break;
		
		default:
		    exit('Invalid extension file!');
	}

    $sBase64 = base64_encode(file_get_contents($sFile));
    return "data:$sMimeType;base64,$sBase64";
}

Initial URL

                                

Initial Description
**Example of use:**
    
    echo base64DataUri('/var/www/html/background.png');

*or*

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

Initial Title
Data URI base64 PHP function

Initial Tags
php, image

Initial Language
PHP