通过.htaccess RewriteRule保护文件夹到php

问题描述

|| 我们正在建立一个在线相册。人们需要登录才能查看图像。我们也在尝试保护图像文件,但我们陷入了问题 通过会话变量,我们检查用户是否已登录
$_SESSION[\'is_ingelogd\'] 
我们构建一个安全页面(用于检查用户是否已登录)。我们将此页面包含在必须保护的每个页面中。但是现在我们也要保护图像。 因此,我们构建了一个.htaccess文件,该文件将照片文件夹中文件的所有请求都引用到PHP页面PHP页面必须检查用户是否已登录。 如果用户登录,它将回显带有登录请求的文本。 如果用户登录,则PHP文件必须发送请求的文件(图像)。 我们使用以下代码执行此操作: .htaccess文件(在/ fotoalbum / uploads /文件夹中):
RewriteEngine On
RewriteBase /fotoalbum/
RewriteCond %{SCRIPT_FILENAME} !image\\.PHP
RewriteCond %{REQUEST_URI} !image\\.PHP
RewriteRule ^(.*)$ image.PHP [QSA,L]
.PHP文件(在/ fotoalbum /文件夹中):
<?PHP
session_start();

if ($_SESSION[\'is_ingelogd\'] == \"1\") {
    $type = mime_content_type((string)$_SESSION[\'REQUEST_URI\']);
    header(\"Content-type: \".$type);
    echo file_get_contents($_SESSION[\'REQUEST_URI\']);
    exit;
} else{
    echo \'Please <a href=\"../login.PHP\">login</a> to see this  
file.\';
}

?>
代码可以工作一半; 如果用户登录并尝试打开/ fotoalbum / uploads /文件夹中的任何文件,则PHP显示登录请求。 但是,如果用户登录,则看不到图片。 在IE9中,屏幕保持空白,在FireFox 3.6中,png返回一条消息,提示无法 由于包含错误显示。 jpg返回其url,而txt文件返回 我们借助以下链接来构建此脚本: http://michael.theirwinfamily.net/articles/csshtml/protecting-images-using-PHP-and-htaccess http://forums.digitalpoint.com/showthread.PHP?t=1492222(#post 12) 谢谢你的帮助 更新: 我做了一些原型设计,and3的返回似乎空白/为空。 我将以下代码放置在PHP文件中:
<?PHP
$serveruri = parse_url($_SERVER[\'REQUEST_URI\']);
$fileuri = (string)(\'./uploads/\'.basename($serveruri[\'path\']).PHP_EOL);
$file = strval($fileuri);

echo \'URL Is: \'.$file;  
echo \'<br />type Is: \'.mime_content_type((string)$file);
exit;
?>
浏览器显示
URL Is: ./uploads/test.jpg
Type Is: 
您会看到它没有回应内容类型。 但是当我设定
$file = \'./uploads/test.jpg\';
它完美地返回:
URL Is: ./uploads/test.jpg
Type Is: image/jpeg
有什么建议吗?     

解决方法

通过本主题的许多技巧,我使它起作用。 但是,它现在可以与URL中的查询字符串一起使用。 文件夹fotoalbum / uploads /中的.htaccess文件:
Options -Indexes
<Files *>
  deny from all
</Files>
文件夹/ fotoalbum /中的getfile.php文件:
<?php

//this file checks if user is logged in and dies the request if the user is not logged in
include_once(\'./config.php\');

$file = \"uploads/\" . $_GET[\'f\'];
$type = mime_content_type($file);

header(\"Content-type:\" .$type);
echo file_get_contents($file);

?>
要获取图像(或任何类型的文件),URL为
getfile.php?f=file.extension
(其中file.extension是fotoalbum / uploads /文件夹中的文件)。 非常感谢大家的帮助!     ,你好 我正在这里拍照,但是您是否检查过确保mime_content_type返回的文件的正确mime类型?看起来如果该声明
header(\"Content-type: \".$type);
输出不正确,则图像或文本文件也将无法正确通过。 PHP.net指示已弃用mime_content_type函数,因此您可能想尝试finfo_file函数。 祝好运!     ,我猜PHP文件与BOM一起保存,而没有BOM则保存。 为什么我这么猜:看起来像BOM     ,将图像和其他二进制文件流回客户端时,应使用readfile()而不是echo file_get_contents()。 更新: mime_content_type()存在的问题是由于PHP_EOL添加了换行符。还有很多不必要的类型转换。以下是适合您的清理版本:
<?php
$serveruri = parse_url($_SERVER[\'REQUEST_URI\']);
$file = basename($serveruri[\'path\']);


echo \'URL Is: \' . $file;  
echo \'<br />type Is: \' . mime_content_type($file);

exit();
?>