尝试找出如何保护目录中的图像 - 我发现这篇文章很有帮助,但不完全满足要求。
我按照文章的指示进行操作,似乎有效,唯一的问题是,如果用户知道图片目录,则可以直接请求图片并查看或下载它。
非常感谢您的任何帮助。
以下是代码:
我按照文章的指示进行操作,似乎有效,唯一的问题是,如果用户知道图片目录,则可以直接请求图片并查看或下载它。
非常感谢您的任何帮助。
以下是代码:
image.php
<?php
if (!isset($_GET['onlyHappensFromHTACCESS'])) {
$_GET['f'] = "protectedImages/" . $_GET['f'];
$type = getFileType($_GET['f']);
if (acceptableType($type)) {
if (goodTiming()) {
header("Content-type: $type");
echo file_get_contents($_GET['f']);
exit;
}
}
header('HTTP/1.1 403 Forbidden');
exit;
}
function getFileType($file) {
if (function_exists("mime_content_type"))
return mime_content_type($file);
else if (function_exists("finfo_open")) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $file);
finfo_close($finfo);
return $type;
}
else {
$types = array(
'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
'gif' => 'image/gif', 'bmp' => 'image/bmp'
);
$ext = substr($file, strrpos($file, '.') + 1);
if (key_exists($ext, $types)) return $types[$ext];
return "unknown";
}
}
function acceptableType($type) {
$array = array("image/jpeg", "image/jpg", "image/png", "image/png");
if (in_array($type, $array))
return true;
return false;
}
function goodTiming() {
$n = time();
session_start();
if ($n - $_SESSION['lastcheck'] > 2 )
return false;
return true;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Image Denied</title>
<style type="text/css" media="screen">
body {
background-color: #ccc;
font-family: Helvetica, Arial;
}
#wrapper {
margin: 30px auto;
background-color: #ffffff;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border-radius: 15px;
width: 800px;
padding: 20px;
}
</style>
</head>
<div id="wrapper">
<h3>Access Denied!</h3>
You have tried to access an image, but due to security reasons, you cannot view the image.
If you wish to use the image you requested, please contact me.
</div>
</html>
index.php
<?php session_start(); $_SESSION['lastcheck'] = time(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<style type="text/css">
.image {
overflow: hidden;
position: relative;
float: left;
}
.image .cover, .image .cover img {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="image">
<img src="image.php?f=cake.png" alt="Image" />
<div class="cover"><img src="imageCover.gif" alt="" /></div>
</div>
</body>
</html>
主文件夹中的htaccess
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^$
RewriteCond %{SCRIPT_FILENAME} image\.php
RewriteRule (.*) image.php?onlyHappensFromHTACCESS=denied [QSA,L]
在protectedImages文件夹中使用htaccess
#Prevent directory listing
Options -Indexes
#Prevent images from being viewed
<Files *>
deny from all
</Files>