I am trying to load in an image in a <img> tag within HTML.
My images folder is in the same folder as the root folder, meaning I need to go up one folder to access the images folder.
I looked around the internet and found the method using GET requests within the src attribute from the image, unfortunately without success.
Folder Structure:
img >
somefile.png
foo.png
bar.png
html >
index.php
imageRequest.php
//other root files
I cannot use the following: <img src="../img/somefile.png"> because it points towards to something non existant (duh!). So I attempted to use the GET request.
My HTML
<div>
<img src="imageRequest.php?requested=somefile.png">
</div>
My PHP (imageRequest.php)
$fileName = $_GET['requested'];
fetchImage();
function fetchImage(){
global $fileName;
if(!isset($fileName)) return;
$filePath = dirname($_SERVER['DOCUMENT_ROOT'])."/img/".$fileName;
if(file_exists($filePath)){
readfile($filePath);
}
}
TL;DR: Use image from folder outside the root folder within the <img> tag.
Get that image using PHP as base64 image and output that content along with proper headers:
[imageRequest.php?requested=some_file.png]
$imagesDir = __DIR__.'/../';
$content = file_get_contents($imagesDir.$_GET['requested']);
$content = base64_encode($content);
$data = "data:image/png;base64,{$content}";
header('Content-Type: image/png');
echo base64_decode($data);`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With