简体   繁体   中英

display image from HTML page using PHP without calling PHP script or using PHP echo to hide image path

I want to display images, from files, in an HTML webpage, using PHP to hide the location of the files, using PHP header/readfile, and avoiding any PHP that would reveal the file location (such as echo).

So far I've only been able to get this working by calling a PHP scrpit from the HTML, but would prefer to do so without calling a script, so a viewer has no sight of the PHP script file. I do not want to use a PHP file rather than HTML file (so a viewer couldn't type the URL of the PHP script in themselves).

image.php:

<?php
header('Content-Type:image/jpeg'); 
readfile('../image.jpg');
?>

image.html:

<html>
...
<img src="image.php"/>

In the HTML file I would like to do the equivalent but in-line:

<html>
...
<img src="<?php header('Content-Type:image/jpeg');readfile('../image.jpg');?>"/>

Or:

<html>
...
<?php
echo '<img src="';
header('Content-Type:image/jpeg'); 
readfile('../image.jpg');
echo '"/>';
?>

I suspect my lack of understanding of how HTML and PHP work together is letting me down here.

I would like to do the equivalent but in-line:

You cannot. You must have separate request. You could optionally inline the image as base64 but that bad idea anyway.

Also this code looks like pointless - you just exposing existing file w/o any benefit of doing that yourself BUT with the penalty of killing all the caching and other features browsers could do. Unless you know how to do that properly (this is not that trivial), you are complicating simple thing instead of simplifying complicated.

What you want can not be done as you're trying. You can echo the contents via the base64 aproach. but that would make your html grow in size very rapidly, which isnt good for performance.

There is a way you can get it to work though. It's a bit trickier, but you can use your .htaccess file for this. Normally you often use it to rewrite some url to redirect the url to the index.php . You can also use it to create an image url:

RewriteEngine On
RewriteRule ^/special-images/(.*)\.jpg$ /php-file-directory/image.php?image-name=$1 [L]

If you now do <img src="/special-images/bob.jpg" /> it will internally open-image.php with $_GET['image-name'] being bob .

*Cant test the htaccess right now, but you get the gist of it.

try coverting it to a data url

https://stackoverflow.com/a/13758760/11485791

example:

<img src="<?
php path = '../image.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;
?>"/>

but then the returned html would be huge

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM