2

I have successfully blocked access to a folder directory outside of WordPress based on user cookies using the following code in the .htaccess file:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]

RewriteCond %{REQUEST_URI} ^.*docs/.*
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
RewriteRule . /wp-login.php?redirect_to=%{REQUEST_URI} [R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

I'm trying to make it more like this solution to have it load a php file to check if the user is logged in and the serve up the page content. That method I link to works to redirect, but I'm not sure how to modify the code to make it load the URL (not an image file like the code was written for). When I use the dl-file.php code as-is, the URL loads as 404.

I'm just not skilled in writing PHP to know how to modify it to say 'load URL'. Any thoughts?

Thanks.

1 Answer 1

2

I like your solution checking the coockie from the .htaccess this will give a much quicker loading solution then my solution.

.htaccess

<IfModule mod_rewrite.c> 
  RewriteEngine On
  # Rules to prevent php execution in uploads  
  RewriteRule ^(.*)/uploads/(.*).php(.?) - [F]  

  #redirect all FILES for login check (excluding PHP)  
  RewriteCond !^(.*)/uploads/([0-9]+/.*)\.php(.?)$ - [NC]  
  RewriteRule ^(.*)/uploads/([0-9]+/.*)\.* /wordpress/file.php?img=$2 [L]
</IfModule>

file.php

<?php
// load wordpress
require_once('wp-load.php');

if( is_user_logged_in() ):
    $file =  ABSPATH.'/wp-content/uploads/'.$_GET['img'];
    if (file_exists($file)) 
    {
        $ftype = 'application/octet-stream'; 
        $finfo = @new finfo(FILEINFO_MIME); 
        $fres = @$finfo->file($file); 
        if (is_string($fres) && !empty($fres)) { 
           $ftype = $fres; 
        } 
        header('Content-Type: ' . $ftype);
        header('Content-Length: '.filesize($file));
        header('Content-Disposition: filename='.basename($file));
        send_nosniff_header();
        flush();
        readfile($file);
    }
    else
    {
        global $wp_query;
        $wp_query->set_404();
        status_header(404);
        include( get_query_template( '404' ) );
    }
else:  
    auth_redirect();
endif;
die();
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.