Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate users before downloading files?

Tags:

php

For example, if users want to download /webroot/files/bigimage.jpg, they are given a URL www.domain.com/download.php?filename=bigimage.jpg. Then,

  1. How to prevent unauthenticated users to access the file bigimage.jpg?
  2. If an authenticated user visits that URL, I want to trigger the download behavior of browsers (e.g., in IE, show the dialog with "Open", "Save" and "Cancel" buttons) instead of displaying the image in browsers. How to do this?

EDIT: Make the question more clearer.

I am using LAMP stack. For Q1, I am not asking how to do authentication, I am asking how to prevent users access the file directly. Also, reading contents of the whole file and echo them is resource extensive. Is there better solution?

like image 631
powerboy Avatar asked Dec 05 '25 20:12

powerboy


2 Answers

First step, drop a .htaccess file in the folder with the image that says "deny from all". This will prevent anyone from access the file even if they know the folder.

Then, you write use a PHP function like this

$file = 'path/to/folder' . $filename;
//Make sure you check that $filename does not contain ".." for security
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
} else {
    //Show error message
}

You should be checking session variables to see if the user is logged and has a role that can download this. This code will also force download of the image than show it.

like image 111
Nigel Avatar answered Dec 08 '25 10:12

Nigel


  1. Use sessions.
  2. Set the header's content META tag to binary so browsers won't try to handle the file on their own.

    header('Content-Type: application/binary');

like image 33
BlueDog Avatar answered Dec 08 '25 12:12

BlueDog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!