[英]PHP / HTML - Load image from outside root folder
我正在嘗試在HTML中的<img>
標記中加載圖像。 我的圖像文件夾與根文件夾位於同一文件夾中,這意味着我需要上一個文件夾才能訪問圖像文件夾。
我環顧互聯網,發現該方法在圖像的src屬性中使用GET請求,遺憾的是沒有成功。
文件夾結構:
img >
somefile.png
foo.png
bar.png
html >
index.php
imageRequest.php
//other root files
我不能使用以下內容: <img src="../img/somefile.png">
因為它指向不存在的東西(呃!)。 所以我試圖使用GET請求。
我的HTML
<div>
<img src="imageRequest.php?requested=somefile.png">
</div>
我的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:使用<img>
標簽內根文件夾外的文件夾中的<img>
。
使用PHP作為base64圖像獲取該圖像,並輸出該內容以及正確的標題:
[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);`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.