Prevent direct download

Hi, I need to allow file download only to logged in users and prevent direct download to anybody else if not logged.
I searched on google and found different suggestions, someone suggested to place the download directory outside the public directory but it doesn’t suite with my project, so i decided to use a combination of .htaccess and php so i’ve created a new .htacces file:

RewriteEngine On
# you can add whatever extensions you want routed to your php script
RewriteCond %{REQUEST_URI} \.(doc|zip|pdf)$ [NC]
RewriteRule ^(.*)$ /controller.php?filename=$1 [L]

then the controller.php

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {

$file = $_GET['filename'];

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

} else {
    echo "Please log in first to see this page.";

And this is the file where the logged in user can see the link for the file.

$query_view_doc = mysqli_prepare($conn, "SELECT group_file_description, group_file_id, group_file_location, group_file_name, group_file_size, group_file_type, group_file_time FROM group_files WHERE group_file_group=? ORDER BY group_file_time DESC");
mysqli_stmt_bind_param($query_view_doc, 'i', $gruppo);
mysqli_stmt_bind_result($query_view_doc, $gr_file_desc, $gr_file_id, $gr_file_location, $gr_file_name, $gr_file_size, $gr_file_type, $gr_file_time);

        while (mysqli_stmt_fetch($query_view_doc)) {  

                           // Coverto la data di creazione del documento per la visualizzazione in un formato europeo
                        $new_file_date = date('M d, Y h:i A', strtotime($gr_file_time));
                        $new_file_time = date_time_ago($new_file_date);

                        $filename = substr($gr_file_location, 11);

                        	echo '
                                    <td><a class="edit" href="'.BASE_URL.'/documents/controller.php?filename='.$filename.'"> <button class="btn btn-sm blue"> <i class="fa fa-download"></i> Scarica </button>  </a></td>





I don’t understand why it doesn’t work, could someone help me please? many thanks

What happens right now, for both logged in and anonymous user? Does it get redirected to the controller or simply downloads the file without the rewrite?

what should this mean for anybody not sitting at your desk?

Hi, thanks for answering it seems to work fine now. Maybe was just the server that was playing up :wink: thanks anyway :wink:

Hi I’ve maged to sort it out sorry to trouble you :wink:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.