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>

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.