简体   繁体   English

PHP阻止直接访问文件,但仍在下载脚本中使用

[英]PHP prevent direct access to file but still use in download script

I have simple download script (used for Wordpress file downloads 我有简单的下载脚本(用于Wordpress文件下载)

if($filesize) {
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary"); 
        header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
        readfile($file_url);
    } else {    
        echo '<p>No file found</p>';
    }

I want to prevent users from accessing download files by direct access to them, so if user types in the path in browser, file should not be accesible. 我想防止用户通过直接访问来访问下载文件,因此,如果用户在浏览器中的路径中键入文件,则该文件将不可访问。

I've tried this with .htaccess but without results. 我用.htaccess尝试过,但是没有结果。 It was blocking the file directly but also script won't download the file. 它直接阻止了文件,但是脚本不会下载文件。

Any help? 有什么帮助吗?

Thanks! 谢谢!

如果文件与PHP脚本位于同一框,请将其移出Web服务器目录,以便脚本可以访问它们,但用户不能访问它们。

i will assume that User need to click certain button to get the file ,means a post method ,and if not from post you show theme an error message, 我将假设用户需要单击某些按钮来获取文件,这意味着发布方法,如果不是从发布中显示错误消息,

if($_SERVER['REQUEST_METHOD'] != 'POST'){
   echo 'Error: You cannot access this link Directly';
}

im also assuming you have your files on separate Folder where you can create new .htaccess file with the following rules: 我还假设您将文件放在单独的文件夹中,可以使用以下规则在其中创建新的.htaccess文件:

Order Deny,Allow
Deny from all

to solve this issue what you can do is you can keep the script file out of folder where download files and .htaccess files are located. 要解决此问题,您可以做的是将脚本文件放在下载文件和.htaccess文件所在的文件夹之外。

By doing so users cant access download file directly if user types in the path in browser, file will not be downloaded. 这样,如果用户在浏览器中键入路径,则用户将无法直接访问下载文件,因此不会下载文件。 they can only access files via script. 他们只能通过脚本访问文件。

hope it makes sense. 希望有道理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM