一个让用户从我的网站下载文件而不泄露我网站中实际文件链接的 PHP 脚本?

2022-01-02 00:00:00 file download php scripting hide

问题说明了一切.. 我如何让用户从我的网站下载文件而不是不让他们看到该文件来自哪个链接?我知道可能需要像 download.php 这样的东西作为网关,但是过了那个阶段,我不知道接下来要编写什么脚本......代码,我应该需要使用的几个函数名称真的很方便!

The question says it all.. How do I let the users download a file from my website and not let them see what link that file comes from? I understand that there might be a need for something like a download.php which will serve as the gateway but past that phase, I dunno what to script next... If it bothers you to write the whole code, a few function names that I should need to use would be really handy!

推荐答案

找到一种方法来识别要下载的文件(例如,与数据库中某行的 ID 匹配的 GET 变量,或类似的东西).确保它是有效的,因为您不希望您的用户能够从您的站点下载任何内容.然后,使用 headerContent-Disposition 告诉浏览器应该下载文件,readfile 输出它.

Find a way to identify the file to download (for instance, a GET variable that matches the ID of a row in a database, or something along these lines). Make damn sure it's a valid one, because you don't want your users to be able to download anything off your site. Then, use header with Content-Disposition to tell the browser the file should be downloaded, and readfile to output it.

例如:

<?php

$id = intval($_GET['id']);
$query = mysql_query('SELECT file_path FROM files WHERE id = ' . $id);
if (($row = mysql_fetch_row($query)) !== false)
{
    header('Content-Disposition: attachment; filename=' . basename($row[0]));
    readfile($row[0]);
}
exit;

?>

相关文章