revo
revo

Reputation: 48711

Let download file if authenticated

I've a RewriteRule in .htaccess file:

RewriteRule ^folder/(.*)$ folder/handle.php?path=$1 [L]

To authenticate users with handle.php file and see if they've premium accounts or not.

I want to [1] check if the user is not authenticated then page show an error, otherwise [2] download get start & I don't want to use any PHP class or script to handle files downloading (just normal server side downloading without php handling).

How can I achieve that? Is it possible?

A URL to request a file download : http://mywebsite.com/folder/file.zip

Upvotes: 4

Views: 2538

Answers (1)

Rob W
Rob W

Reputation: 9142

The rewrite rule you have there is fine... except you should probably add a condition to check and make sure the REQUEST is not "handle.php" - otherwise you may get a redirect loop.

Now, in your handle.php file - this is handling ALL files request in that folder.

In handle.php, you can use $_GET['path'] to get the requested file name. While in handle.php, you can include your authentication checks. If the authentication check passes, you can then continue to readfile to the user. An example of handle.php:

<?php
set_time_limit(0);
session_start();
include "../some_functions_auth_file.php";

// NOTE: better file checking should be implemented here. We're using basename() for now.
$file = !empty($_GET['path']) ? basename($_GET['path']) : false;
if($file === false || !file_exists($file)) die("Invalid file.");

if(user_is_authenticated()) {
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
  header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); 
  header("Cache-Control: no-store, no-cache, must-revalidate"); 
  header("Cache-Control: post-check=0, pre-check=0", false ); 
  header("Pragma: no-cache" ); 
  header("Content-Type: application/octet-stream");
  header("Content-Length: " .(string)(filesize($file)) );
  header('Content-Disposition: attachment; filename="'.$file.'"');
  header("Content-Transfer-Encoding: binary\n");
  readfile($file);
  exit;
} else {
  header("Location: ../login.php");
}
?>

Note that this is very basic and untested

Now, if you don't want to use readfile (because it's, well, slow), then perhaps you could set an Apache environment variable... then, while in .htaccess, you could check if that variable exists - and if so, allow the download. Otherwise redirect the user to a login.

Upvotes: 1

Related Questions