I am trying to insert an image from my server as a background image converted to base64.
I receive these errors:
Warning: filesize(): stat failed
Warning: fread(): Length parameter must be greater than 0
I have read that both errors can be caused by the files not being writeable, but I have made all files related writeable (the image file, the folder it is in and the file the code is on) and still no joy.
This is the php code
<?php
$img_source = "image.jpg";
$img_binary = fread(fopen($img_source, "r"), filesize($img_source));
$img_string = base64_encode($img_binary);
?>
And here is my css/php
body { background-image:url('data:image/gif;base64,<?php echo $img_string; ?>');
I was previously achiving the result I wanted by using get_file_contents but it was very very slow. This was my old method.
<?php echo base64_encode(file_get_contents($img_url.'/'.$image)) ?>
With the file_get_contents
you were on the right track but it seems you were actually using the URL, not just the file path (thus file_get_contents
used HTTP to get the file contents). Try changing it to this:
<?php
$img_source = "image.jpg";
$img_string = base64_encode(file_get_contents($img_source));
?>