Secure file download in PHP, deny user without permission(PHP中的安全文件下载,未经许可拒绝用户)
问题描述
我正在制作一个网站,您可以在其中购买虚拟点的文件,然后下载它们.我不想让用户不购买就下载文件,所以我必须隐藏它们.我把所有文件都放在一个文件夹中,除了主机之外,没有任何人的许可,问题是有人买了一个文件想要下载它.
I'm making a website where you can buy files for virtual points, and then download them. I don't want to let users download the files without buying it, so I have to hide them. I put all the files in a folder without permission for anyone except host, the problem is when someone buys a file and wants to download it.
我决定制作一个文件获取器,它将检查用户的权限,然后打印出文件内容.到目前为止我的代码:
I decided to make a file getter, that will check permissions of user and then print out the file contents. My code so far:
<?php
require_once('content/requirements.php'); //mysql connections
secure(1); //disconnect unlogged users
if (!isset($_GET['id'])) //if no file id provided
die();
$fid=mysql_real_escape_string($_GET['id']); //file id
$query="SELECT * FROM files WHERE user_id = "$_SESSION['user_id']." AND file_id = ".$id;
$q=mysql_query($query);
if (mysql_num_rows($q)!=1) //if no permission for file or multipe files returned
die();
$file=mysql_fetch_array($q); //file id
$sub=mysql_fetch_array(mysql_query("SELECT * FROM sub WHERE id = ".$file['file_id'])); //payment id
?>
现在,当我确定用户有权执行此操作时,phpScript 应该写入文件内容并发送适当的标头让用户下载.
Now when Im sure the user is authorized to do this, phpScript should write the file contents and send appropiate header to let user download it.
如何逐字节读取文件并打印它以及我应该在 header() 中写什么,以使文件可下载(因此您不必复制粘贴其内容).
How to read file byte-by-byte and print it and what should i write in header(), to make the file downloadable (so you don't have to copypaste its contents).
也许这不是最好的方法,但这是我一段时间以来想到的最好的方法.
Maybe this is not the best way to do this, but it was the best thing I thought of in a while.
感谢您的帮助.
推荐答案
来自 readfile php doc
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
这篇关于PHP中的安全文件下载,未经许可拒绝用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP中的安全文件下载,未经许可拒绝用户


基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01