在会话中提供文件下载

时间:2014-05-17 09:23:36

标签: php

我正在尝试使文件下载依赖于会话。这是代码:

<?php>
    session_name("My-Download");

    session_start();

    $_SESSION['Download-Authorized'] = 1;

    echo "<a class='invlink' rel='nofollow' download target='_blank' href='download.php?download_file=file.to.download.pdf'>Name of File</a><br /><br />";

?>

接下来是下载脚本(&#39; download.php&#39;):

<?php
    session_start();
    if(!isset($_SESSION['Download-Authorized'])) {
        exit;
    }
    $path = $_SERVER['DOCUMENT_ROOT']."/downdir/"; 
    $fullPath = $path.$_GET['download_file'];

    if ($fd = fopen ($fullPath, "r")) {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Type: application/pdf");
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . $fsize);

        while(!feof($fd)) {
            $buffer = fread($fd, 2048);
            print($buffer);
            flush();
        }
        fclose ($fd);
    } else {
        die("File does not exist. Make sure you specified correct file name.");
    }
    exit;
?>

只要注释了&#39; $ _ SESSION [&#39;下载 - 授权&#39;]的验证,一切正常。 当我检查会话变量时,设置了$ _SESSION [&#39;下载 - 授权&#39;] 下载将失败。

我的代码出了什么问题?

任何帮助表示感谢。

将session_start()添加到download.php的开头后,脚本仍然无效。 似乎是会话ID以及会话名称在&#34; download.php&#34;叫做。此外,$ _SESSION [&#39; Downlad-Autorized&#39;]被重置。

1 个答案:

答案 0 :(得分:1)

您的初始脚本将标记存储在明确重命名的会话(session_name("My-Download");)中,但下载脚本使用默认会话名称(无session_name())。

因此,您的下载脚本以另一个(可能为空)会话开始。