在PHP中安全的文件下载,未经许可拒绝用户 [英] Secure file download in PHP, deny user without permission

查看:151
本文介绍了在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.

我决定做一个文件getter,这将检查用户的权限,然后打印出文件内容。我的代码到目前为止:

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.

Thanx为任何帮助。

Thanx for any help.

推荐答案

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中安全的文件下载,未经许可拒绝用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆