限制网站中的图片访问,通过.htaccess和PHP限制用户访问特定图片。

huangapple go评论93阅读模式
英文:

Restrict images access in my website limit the user to access specific image by htaccess and php

问题

我正在开发一个聊天网站,其中有发送图片给用户的功能,这些图片将保存在用户文件夹中,例如user/newuser/a.jpg(意思是每当用户注册时,我会在主用户文件夹内创建一个名为user/newuser的文件夹)。

但问题出在这里,这张图片只应该由发送者和接收者查看,而不应被所有人看到,但每个人都可以通过URL轻松查看这张图片,例如http://localhost/chat/user/abc.jpg。
因此,我想到了通过.htaccess限制对用户文件夹的访问,并将所有请求重定向到user/index.php的方法。

RewriteRule ^user(/.*)?$ user/index.php [QSA] 

然后在user/index.php中,我将使用以下代码将用户重定向到user/username/userimage.jpg。

session_start();
$imageName = str_replace('/chat/','',$_SERVER['REQUEST_URI']);

if(in_array($imageName,$_SESSION['imageArray'])){

    // $_SESSION['imageArray']包含可以被已登录用户访问的所有图片名称,格式如['user/newuser/abc.jpg','user/newuser/1.jpg',]

    header('location:'.substr($imageName,strrpos($imageName,'/')+1)); // 只输出image.jpg

}
else{
    echo 'you are not allowed to access this resource';
}

但它没有按预期工作,如果用户可以访问图片,它会不断重定向,如果不能访问,则简单地显示'you are not allowed to access this resource'。

现在,如果您理解我的问题,希望告诉我如何实现这一点,如果不能通过.htaccess实现,那么我应该怎么做,以及处理这种情况的最佳高效方式是什么。我不想使用readfile函数来读取文件或类似的东西,因为它会消耗大量服务器资源。非常感谢您的帮助。提前感谢。

我知道.htaccess正在重定向可以访问图片的情况,因为我的.htaccess条件是任何对用户文件夹的请求都应重定向到user/index.php。但我不想重定向在user/index.php内部进行的任何请求以访问用户文件夹中的任何资源。我对.htaccess代码不熟悉,所以如果您能提供任何代码,并解释一下就好了。

英文:

I am working on a chat website which has the feature of sending images to users which would be save into their user folder like this user/newuser/a.jpg (means whenever a user register I create a folder inside a main user folder name like this user/newuser).

But here the problem arises this image is meant to be seen by only sender and receiver not by everyone but everyone with the url can easily seen the image like this http://localhost/chat/user/abc.jpg.
So, I come up with that I would restrict access to user folder with htaccess and redirect all requests to user/index.php with this code.

RewriteRule ^user(/.*)?$ user/index.php [QSA]                                                                                 

and from this user/index.php I will redirect user to user/username/userimage.jpg with this code.

session_start();
$imageName = str_replace('/chat/','',$_SERVER['REQUEST_URI']);

if(in_array($imageName,$_SESSION['imageArray'])){

/**$_SESSION['imageArray'] contains all images name which can be accessed by the logged in user like this 
    *['user/newuser/abc.jpg','user/newuser/1.jpg',]
*/
    header('location:'.substr($imageName,strrpos($imageName,'/')+1)); //just output image.jpg

}
else{
echo 'you are not allowed to access this resource';
}

But it isn't working the way it should be if the user can access image it is ending up redirecting again and again and if not then it simply saying you are not allowed to access this resource.

Now, if you understand my question hopefully tell me how to achieve this and if it can't be achieved with htacess then what should I do and what is the best and efficient way to handle scenarios like this.I don't want to use readfile functions to read file and anything like that because it will consump a lot of server resource.Any help is highly appreciated. Thanks in advance.

I know that htaccess is redirecting when image can be accessed because of my htaccess condition that any request to user folder should be redirect to user/index.php. But I don't want to redirect any request which is made inside user/index.php to access any of user folder resource. I am not good with .htaccess code so any code you provide it would be great if you would explain it too.

答案1

得分: 0

这是一些粗略的示例代码,大致展示了如何存储和检索存储在网站文档根目录之外的文件。

get_file.php

$filename = tempnam('../var/user_file/', 'usrfile_');
move_uploaded_file($_FILES['userfile']['tmp_name'], $filename);
$realname = $_FILES['userfile']['name'];

YourApp::save_user_file_info($filename, $realname);

serve_file.php

if (!YourApp::check_auth()) {
  exit();
}
$some_identifier = $_GET['id'];
$file = YourApp::get_user_filename_info($some_identifier);

session_write_close();
header('Content-type: ' . $file->mimeType);
header('Content-Transfer-Encoding: Binary');
header('Content-length: ' . $file->size);
header('Content-disposition: attachment; filename="' . $file->realname . '"');
readfile($file->location);
exit();

注意:这只是示例代码,可能需要根据您的特定需求进行调整和改进。

英文:

Here is some rough example code that approximates what it might look like to store and retrieve files stored outside the docroot of your website.

/home/someuser/
  - htdocs/
    - get_file.php
    - serve_file.php
  - var/user_files/

get_file.php

$filename = tempnam('../var/user_file/', 'usrfile_');
move_uploaded_file($_FILES['userfile']['tmp_name'], $filename);
$realname = $_FILES['userfile']['name'];

YourApp::save_user_file_info($filename, $realname);

serve_file.php

if( ! YourApp::check_auth() ) {
  exit();
}
$some_identifier = $_GET['id'];
$file = YourApp::get_user_filename_info($some_identifier);

session_write_close();
header('Content-type: ' . $file->mimeType);
header('Content-Transfer-Encoding: Binary');
header('Content-length: ' . $file->size);
header('Content-disposition: attachment; filename="$file->realname"');
readfile($file->location);
exit();

答案2

得分: 0

最后,我提供了一个可行的解决方案。请查看它,如果有任何错误,请在评论中 kindly 通知我。

让我们开始,在 .htaccess 文件中,这一行

RewriteRule ^user(/.*)?$ user/index.php [NC]

将所有来自 user 文件夹的请求重定向到 user/index.php,并在这个文件中,这是我所做的基本示例。

如果($url)在($_SESSION['accessible-images'])中{

header('Content-Type: image');
echo readfile(str_replace('user/','',$imageName)); }
else{
header('location:404'); }

只有使用这段代码的用户可以访问他们被允许访问的图像。任何无法访问图像的人都将被发送到 404 页面。这是我检索图像的代码。

echo '<img src='user/username/userfile.jpg' >';

感谢 Mr Sammitch 的回答,它帮助了我使用 header 函数。如果这个回答或问题对任何人有帮助,请给我的回答和问题投票。谢谢。

英文:

Finally, I come with a working solution. Check it out and if there are any bugs kindly inform me in comments.
Let's Start, this line in .htaccess

RewriteRule ^user(/.*)?$ user/index.php [NC]

is redirecting all requests from user folder to user/index.php and in this file this is the basic example of what I did there.

if(in_array($url,$_SESSION[&#39;accessible-images&#39;)){                
header(&#39;Content-Type: image&#39;);
echo readfile(str_replace(&#39;user/&#39;,&#39;&#39;,$imageName)); }               
     else{ 
   header(&#39;location:404&#39;); }

with this code only user can access the images which they are allowed to access. And anyone who can't access images are sent to 404 page. Here is my code where I am retrieving images.

echo &#39;&lt;img src=\&#39;user/username/userfile.jpg\&#39; &gt;&#39;;

Thanks to Mr Sammitch Answer which help with the header function. If this answer or question would help anyone please upvote my anwer and question too.Thanks

huangapple
  • 本文由 发表于 2023年6月15日 04:54:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定