简体   繁体   English

如何阻止对目录中图像的直接访问,但允许PHP显示它们?

[英]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.

相关问题 PHP:如何阻止对文件的直接URL访问,但仍允许登录用户下载文件? - PHP: How can I block direct URL access to a file, but still allow it to be downloaded by logged in users? 如何允许使用PHP下载文件,但拒绝直接访问目录列表 - How to allow downloading files with PHP, but deny direct access to directory listings 如何阻止 URL 直接访问文件夹中的所有文件,但仍允许用户下载? - How can I block direct URL access to all file in a folder, but still allow it to be downloaded by users? 如何阻止访问PHP网站上的目录? - How can I block access to a directory on my PHP site? 如何允许用户上传多个文本文件,然后将它们保存为字符串并显示(在PHP中)? - How can I allow a user to upload multiple text files, then save them to a string and display them (in PHP)? 阻止通过HTTP直接访问文件,但允许php脚本访问 - Block direct access to a file over http but allow php script access 阻止直接访问PHP文件,仅允许本地javascript访问它 - block direct access to PHP file and only allow local javascript to access it 如何拒绝访问目录中的所有文件,但允许访问其他目录中的特定php文件呢? - How can I deny access to all files in directory but allow access from specific php file in other directory? 如何拒绝直接访问目录,但允许通过php脚本访问目录? - How can I deny direct access to a directory, but allowing it from a php script? 如何阻止对我的 JavaScript 文件的直接访问? - How can I block direct access to my JavaScript files?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM