简体   繁体   English

如何防止用户通过URL查看图像?

[英]How to keep users from viewing images by URL?

Imagine I have an image file secretImage.png on my Webspace and I want several users to have the right to access this image on index.php . 想象一下,我在secretImage.png上有一个图像文件secretImage.png ,我希望多个用户有权在index.php上访问该图像。 This can easily be done: 这很容易做到:

// index.php
if($userIsAllowed) echo '<img src="secretImage.png" />';

The problem is, users could theoretically still access the image by browsing directly to www.myDomain.com/secretImage.png . 问题是,从理论上讲,用户仍然可以通过直接浏览到www.myDomain.com/secretImage.png来访问图像。 Is there any way to prevent them from doing so, so that the image can only be viewed inside index.php ? 有什么方法可以阻止他们这样做,以便只能在index.php内部查看图像?

You can use htaccess to route all requests for a specific folder through a .php file. 您可以使用htaccess通过.php文件路由对特定文件夹的所有请求。 In the file, you can determine whether user can see the file or not... if so, deliver the correct headers and the image. 在文件中,您可以确定用户是否可以看到文件...如果可以,请提供正确的标题和图像。 If not, show whatever you want (404, placeholder image). 如果没有,请显示任何内容(404,占位符图像)。

The HTTP call GET /secretImage.png should itself require authentication. HTTP调用GET /secretImage.png本身应要求身份验证。 For example, you could use basic authenication and have the user send a Authorization: {base64 user:password} header. 例如,您可以使用基本身份验证,并让用户发送Authorization: {base64 user:password}标头。

Serve your images from a php file via fpassthru where you check that the user is allowed 通过fpassthru从php文件提供图像,以检查是否允许该用户

So for example, you might have a php file, getimage.php, that accepts a querystring like "?image=mysecretimage.png" and if the user is allowed, it passes it through. 因此,例如,您可能有一个PHP文件getimage.php,该文件接受诸如“?image = mysecretimage.png”之类的查询字符串,如果允许用户,它将通过它。 If you go this route, be careful to take appropriate precautions that only your image files are passed through. 如果您采用这种方式,请小心采取适当的预防措施,以确保仅通过图像文件。

User-specific URLs can be guarded through HTTP authentication. 可以通过HTTP身份验证来保护用户特定的URL。 There are examples online, and it is entirely possible through some .htaccess fiddling that you tailor this method to all of your existing images. 在线上有示例 ,通过.htaccess修改完全有可能使您针对所有现有图像定制此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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