【问题标题】:Start a download with PHP without revealing file URL使用 PHP 开始下载而不显示文件 URL
【发布时间】:2014-11-21 19:36:41
【问题描述】:

我想使用 PHP 开始下载,但我不希望用户知道正在下载的文件的 URL。

我在 StackOverflow 中阅读了很多答案,但我发现的只是显示下载文件的 URL。

这是我想做的,例如:

这是 PHP 文件,用户会看到这个 URL:http://website.com/download.php

这是下载文件的网址,我不想让用户看到这个网址:http://website.com/file.zip

有什么办法吗?

【问题讨论】:

标签: php url download


【解决方案1】:

这取决于你想隐藏什么。 URL 将永远显示给用户,但如果您不希望用户知道发送哪些参数(或值),您可以对它们进行编码并通过 AJAX 通过 POST 请求发送它们。

【讨论】:

    【解决方案2】:

    试试这个:

        $file = './file.zip';
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"'); //<<< Note the " " surrounding the file name
        header('Content-Transfer-Encoding: binary');
        header('Connection: Keep-Alive');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
    

    【讨论】:

    • 我尝试开始下载视频 (MP4) 文件,它开始下载但立即完成。它下载一个 0 字节的文件。
    • 如果你尝试直接下载是否正常下载/
    • 是的。如果我转到视频并单击另存为,则下载正常开始。
    【解决方案3】:

    在渲染页面之前,将下载 url 存储在某处(例如在会话中)并生成一些唯一的哈希值,稍后您可以使用它来识别应该下载哪个文件:

    $SESSION['file_download']['hash'] = md5(time) . '_' . $userId; // lets say it equals to 23afg67_3425
    $SESSION['file_download']['file_location'] = 'real/path/to/file';
    

    渲染时向用户显示以下下载地址:

    http://yourdomain.com/download_file.php?hash=23afg67_3425
    

    如果用户单击它,您将文件发送给用户,但只允许一次或在当前会话期间。我的意思是你应该创建一个名为 download_file.php 的新源文件,其内容如下:

    if ($_GET['hash'] == $SESSION['file_download']['hash']) {
      // send file to user by outputing the file data to browser
        $file = $SESSION['file_download']['file_location'];
    
        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));
        readfile($file);
    
      // optionaly reset $SESSION['file_hash'] so that user can not download again during current session, otherwise the download with generated link will be valid until user session expires (user closes the browser)
    } else {
      // display error message or something
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多