Categories
CMS Development Wordpress

Prevent guests from accessing files

I’m working on a script to protect uploaded files from being viewed by logged out users. My code is loosely based on this as a starting point. Here’s my current code:

.htaccess:

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(.*)$ file-access.php?file=$1 [QSA,L]

file-access.php:

require_once('wp-load.php');

error_log( 'File access check started.'.PHP_EOL, 3, "file-access.log" );

$file_path = $_SERVER['REQUEST_URI'];
$file = "https://example.com".$file_path;
error_log( 'File being accessed: '.$file.PHP_EOL, 3, "file-access.log" );

if ( is_user_logged_in() ) {

    error_log( 'User is logged in.'.PHP_EOL, 3, "file-access.log" );
    // How do I return the $file normally here?

} else {

    error_log( 'Block file access.'.PHP_EOL, 3, "file-access.log" );
    wp_redirect( home_url() );
    exit();

}

However, I have a few problems.

  1. Is that rewrite rule applying to all subdirectories in the /uploads/ directory?
  2. It seems that is_user_logged_in() isn’t working correctly- any ideas why?
  3. How would it be best to return the file if the user is logged in?

FWIW I’ll be adding some more checks down the line.

Leave a Reply

Your email address will not be published. Required fields are marked *