dongyou1926 2014-02-12 18:11
浏览 30
已采纳

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>
  • 写回答

1条回答 默认 最新

  • douxi4114 2014-02-12 18:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?