php仅在会话/ cookie处于活动状态时允许下载[重复]
This question already has an answer here:
I have provided a straight download link in my site as below.
<a href="myfile.pdf">Download here</a>
This file is accessible to every one. But i want to restrict this based on logged in users.
Say an user have an active session / cookie upon successful login as below.
$_SESSION['login'] = 1 or $_COOKIE['login'] = 1
even if set following condition, people can manually type http://web.com/myfile.pdf and able to download the file...
if($_SESSION['login']===1 && $_COOKIE['login']===1){
echo '<a href="myfile.pdf">Download here</a>';
}
Other Anonymous users should not be able to access the file.
</div>
此问题已经存在 这里有一个答案: p>
-
允许登录用户在PHP下载文件,否则没有人不能
4个答案
span>
li>
ul>
div>
我有 在我的网站上提供了一个直接下载链接,如下所示。 p>
&lt; a href =“myfile.pdf”&gt;在此处下载&lt; / a&gt; code>
每个人都可以访问此文件。 但我想基于登录用户来限制这一点。 p>
说成功登录后用户有活动的会话/ cookie,如下所示。 p>
$ _ SESSION ['login'] = 1或$ _COOKIE ['login'] = 1 code> pre>
即使设置了以下条件,人们也可以手动 输入 http://web.com/myfile.pdf 并下载文件...... strong> p>
if($ _ SESSION ['login'] === 1&amp;&amp; $ _COOKIE ['login'] === 1){ echo' &lt; a href =“myfile.pdf”&gt;在此处下载&lt; / a&gt;'; } code> pre>
其他匿名用户不应该能够 访问该文件。 strong> p> div>
If it were me I would use something like this to hide the link entirely from the not logged in users
if($_SESSION['login']===1 || $_COOKIE['login']===1){
echo '<a href="myfile.pdf">Download here</a>';
}
If you are looking for specific download denying based on the session after the link is clicked, you will have to setup some type of script to handle the above code and return the file you want.
EDITED:
OK, then link it to a script that retrieves the file from a non-accessible location and feeds it back with the same if/then statement.
Something like
filedownload.php?filename=foo.bar
And then filedownload.php would look something like this.
<?php
session_start();
if($_SESSION['login']===1 && $_COOKIE['login']===1){
$file_dir = "/some/dir/";
$file = $file_dir . 'foo.bar';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
} else {
echo "You need to login to download this file.";
}
?>
This was copied directly from the PHP manual. And added the if/then statement.