Friday, July 3, 2020

How to Embed an Image In HTML Page Using PHP

Sometimes, you might want to get a self-contaned HTML page that does not have to send a request to fetch an image from your server. This also can be helpful if you want to send HTML emails. To embed an image, first we have to read the image file and then encode it in base 64 and then add to to our HTML. The following code sample shows how to do it.
$file = 'path/to/my/file/image.jpg';
$rawData = file_get_contents($file);
$encoded = base64_encode($rawData);
echo '<img src="data:image/jpg;base64,'.$encoded.'" >';