[英]How can I block direct access to images in a directory but allow PHP to display them?
I'm using a .htaccess file with the following code: 我正在使用带有以下代码的.htaccess文件:
Order deny, allow
Deny from all
Allow from localhost
But when I display the images I'm just putting a link to the image in an tag, but the images are not showing up. 但是,当我显示图像时,我只是在标签中放置了指向图像的链接,但是图像没有显示出来。
How can I display the image but disallow direct access to it? 如何显示图像但不允许直接访问它? Is there a way for me to just copy the raw bytes of the file and display them?
我有什么办法可以只复制文件的原始字节并显示它们吗?
Be sure to save embedded.png in same folder as this example source. 请确保将Embedded.png与该示例源保存在同一文件夹中。
<?php
function data_uri($file, $mime)
{
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
?>
<html>
<h1>Embedded Image:-</h1>
<img src="<?php echo data_uri('embedded.png','image/png'); ?>" alt="Embedded image" />
</html>
Send the appropriate Content-Type
header for the image, and then use readfile()
to stream the bytes to output. 发送适当的图像的
Content-Type
标头,然后使用readfile()
传输要输出的字节。
Also, if you're going to use a filepath in the URL for this, be certain to sanitize the filepath first so that eg /etc/passwd
can't be read using your script. 另外,如果您打算为此在URL中使用文件路径,请确保首先清理该文件路径,以使例如
/etc/passwd
无法使用您的脚本读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.