Let the download file complete

I have a RewriteRule in a .htaccess file:

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

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

I want [1] to check if the user has been authenticated, and then the page shows an error, otherwise [2] download to start, and I don’t want to use any PHP class or script to handle file uploads (just normal server-side upload without php processing )

How can i achieve this? Is it possible?

URL for file upload request: http://mywebsite.com/folder/file.zip

+4
source share
1 answer

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

Now, in your file handle.php is the processing of ALL file requests in this folder.

In handle.php, you can use $_GET['path'] to get the requested file name. Although in handle.php you can enable authentication. If authentication passes, you can go to the readfile user. Example 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 MYH: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"); } ?> 

Please note that this is very simple and untested.

Now, if you do not want to use readfile (because it is, well, slow), then perhaps you can set the Apache environment variable ... then, while .htaccess, you can check whether this variable exists - and if so, allow the download. Otherwise, redirect the user to login.

0
source

Source: https://habr.com/ru/post/1488735/


All Articles