拒绝访问特定文件但允许在登录后访问该文件

时间:2016-11-12 11:18:20

标签: php pdf hyperlink access-denied

我想拒绝访问文件! 我发送了一个pdf链接给朋友:http://www.domain.com/pdf/name.pdf 当我的朋友尝试访问该pdf链接时,我想拒绝访问并重定向到登录页面,此后我插入用户名和密码来访问该pdf!

谢谢你!

更新:在我搜索并阅读了一些我喜欢的东西并且工作很漂亮之后,上面是代码:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomainname/pdf/ [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomainname/pdf/.*$ [NC] 
RewriteRule ^pdf(/.*)\.(gif|jpg|pdf)$ - [F]
ErrorDocument 403  /error/index.php

2 个答案:

答案 0 :(得分:1)

你应该使用简单的.htaccess身份验证

/path/to/pdf/.htaccess

AuthType Basic
AuthName "protected area"
AuthUserFile /path/to/pdf/.htpasswd
Require valid-user

/path/to/pdf/.htpasswd

密码必须加密并使用base64编码。

myusername:$apr1$EzX1xHNv$NgbgAnflbfzjI0Vhxwv8q.

您可以运行以下PHP脚本以获取htpasswd文件的正确密码值

<?php
// Password to be encrypted for a .htpasswd file
$clearTextPassword = 'some password';

// Encrypt password
$password = crypt($clearTextPassword, base64_encode($clearTextPassword));

// Print encrypted password
echo $password;
?>

当有人试图连接到此网址时,系统会提示他们进行身份验证

enter image description here

答案 1 :(得分:0)

在下载PDF文件之前,您需要在服务器端放置一些逻辑,首先需要一个服务器页面来检查用户是否已登录(在php手册中检查会话),仅当用户执行了会话时登录以下载pdf文件(检查从php下载pdf文件),如果用户未登录,则将用户重定向到登录页面,最后在登录页面服务器端,当您检查用户是否有效时例如,从数据库设置会话中的用户数据。

一个非常简单的例子是这样的:

//donwloadpdf.php
if (session_status() == PHP_SESSION_NONE) {

    session_start();
}

if (!isset($_SESSION['user_id'])) { //user not logged in

    redirect('login_page.php');

}

//user logged in
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("PD_FILE.pdf");

您需要阅读有关会话和下载文件的内容,还需要将登录信息放在具有自己负责的对象中。

在服务器端你的login_page.php的一些非常简单的例子将是这样的:

//login_page.php
//if is POST
//put some real logic to check if the user is valid
if (true) {

    $_SESSION['user_id'] = 1; //put real data from database

}
//end of logic to check if the user is valid
相关问题