Embedding images in HTML or CSS with PHP

This small function returns an encoded string to embed images, inline, inside your html/css code and reduce the number of…

December 4, 2013

This small function returns an encoded string to embed images, inline, inside your html/css code and reduce the number of calls to the server and speed up page load.

function encodeimg($file) {
	$contents = file_get_contents($file);
	$base64 = base64_encode($contents);
	$imagetype = exif_imagetype($file);
	$mime = image_type_to_mime_type($imagetype);
	return "data:$mime;base64,$base64";
}

Example of usage to inline an image:

echo "<img src='".encodeimg("minibots/avatar.jpg")."'/>";

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

Block junk emails, spammers and temporary emails

If you need an Email Validator Function, consider this version that includes also the check against common temporary mail services…

December 3, 2013

User agent detect with PHP

Small PHP code snippet to make a quick detect if the browser that requests your page is on a mobile…

November 7, 2013

PHP function to fix collation on database fields of MySQL

This PHP function search for tables in the active db, match table’s name with the regular expression passed as first…

February 11, 2010

Stop sending email to new user in WordPress admin registration

Prevent WordPress to send notification emails when you manually create new users

March 9, 2017

Add Internet Explorer class to body to detect old browser

When you have clients that still uses an old browser, you need to handle it. This javascript function detects the…

February 27, 2017

Add filter on wp_title not working with Yoast SEO plugin

For SEO purposes, in a specific template that has a list of items with pagination, I need to have different…

February 22, 2017