Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure file download in PHP, deny user without permission

Tags:

file

php

download

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
?>

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.

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 for any help.

like image 480
noisy cat Avatar asked Nov 19 '12 12:11

noisy cat


2 Answers

from 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;
}
like image 137
Luca Rainone Avatar answered Nov 02 '22 22:11

Luca Rainone


There are many script available on google, Below are few links:

http://www.tutorialchip.com/php-download-file-script

http://www.webinfopedia.com/php-file-download-script.html

like image 29
VibhaJ Avatar answered Nov 02 '22 22:11

VibhaJ