A PHP script to let users download a file from my website without revealing the actual file link in my website?

后端 未结 4 1687
暖寄归人
暖寄归人 2020-11-30 09:19

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 the

相关标签:
4条回答
  • 2020-11-30 09:57

    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.

    For instance:

    <?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;
    
    ?>
    
    0 讨论(0)
  • 2020-11-30 10:06

    readfile should do what you want. Put the actual file outside the web server root, and require some credentials before passing back the file.

    0 讨论(0)
  • 2020-11-30 10:08

    You can use the header() function which is documented here

    I would suggest scrolling down and looking at the 1st example. It seems to be doing exactly what you want.

    0 讨论(0)
  • 2020-11-30 10:13

    You can't make someone download a file from a URL without letting them know the URL. It's not possible under the HTTP specification. Anything downloaded has a URL.

    You can, however, have a download URL that only works once, or requires some specific information to be passed via the POST method. You check for a token in the GET or POST variables and invalidate that token once it's used once.

    0 讨论(0)
提交回复
热议问题