我想知道如何在图像中添加哈希,以便仅在存在哈希的情况下显示图像?
以下是实现此逻辑的现有示例http://193.0.171.27/13/80/98/1504890831/1531993942_square.jpg?hash=pPGpdsy8NJK1w0sq04Xjzw&过期=64060578000
只有当url中存在哈希时,才会显示上面的图像,否则该图像将被禁止。
有人知道怎么做吗?
我看到了两种可能性,你可以重写所有的图像链接,并从php提供它,例如:
之前:
<img src="yourimagefolder/1531993942_square.jpg" />
之后:
<img src="/getimages.php?n=1531993942_square.jpg&hash=somehash" />
因此,您可以询问hash是否已设置并且有效,然后通过php返回图像,在这里您可以找到一些示例:fpassthru()。如果这是您想要的解决方案,则必须将.htaccess
文件放在映像目录中,这样就没有人可以直接访问映像。
.htaccess
Deny from all
另一个解决方案是获取链接的现状,并用.htaccess
进行重写,在这里您可以找到一些信息:
- Apache-使用.htaccess将图像重写到php文件
- 根据文件通过.htaccess重定向映像请求存在
- .htaccess将图像文件重写为php脚本
示例(如何工作):
文件树
public_html
|--images
|-- example.jpg
|-- .htaccess
|-- image.php
|-- file that include the images
|-- some other files
|-- ....
.htaccess
RewriteEngine on
RewriteRule (.*?'.jpe?g|png|gif|ico|bmp)$ image.php?image=$1&%{QUERY_STRING} [L,NC]
image.php
$serveFile = false;
if( isset( $_GET["image"] ) && isset( $_GET["hash"] ) ) {
// check hash, just for example used md5
$image = trim( $_GET["image"] );
$file = dirname( __FILE__ ).'/'.$image;
$imagehash = md5( $image );
if( $imagehash === trim( $_GET["hash"] ) && file_exists( $file ) ) {
// serve the file
$serveFile = true;
}
}
if( $serveFile ) {
// BEWARE you have to send the right header,
// maybe create an array with the content types for extensions
// or get a mime type function which returns this i.e.:image/jpg or some other type
header("Content-Type: image/jpg");
header("Content-Length: " . filesize( $file) );
readfile( $file );
// exit;
} else {
// just sends a header, maybe you have to output a 403 page
header('HTTP/1.0 403 Forbidden');
// here you can include your own 403 page
// include "/path/to/my/403.html";
exit;
}
您应该根据需要调整.htaccess
。