Skip to content

Instantly share code, notes, and snippets.

@hakre
Created January 2, 2012 21:41
Show Gist options
  • Save hakre/1552239 to your computer and use it in GitHub Desktop.
Save hakre/1552239 to your computer and use it in GitHub Desktop.
Wordpress login to download uploaded files
<?php
/*
* dl-file.php
*
* Protect uploaded files with login.
*
* @link http://wordpress.stackexchange.com/questions/37144/protect-wordpress-uploads-if-user-is-not-logged-in
*
* @author hakre <http://hakre.wordpress.com/>
* @license GPL-3.0+
* @registry SPDX
*/
require_once('wp-load.php');
is_user_logged_in() || auth_redirect();
list($basedir) = array_values(array_intersect_key(wp_upload_dir(), array('basedir' => 1)))+array(NULL);
$file = rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:'');
if (!$basedir || !is_file($file)) {
status_header(404);
die('404 &#8212; File not found.');
}
$mime = wp_check_filetype($file);
if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) )
$mime[ 'type' ] = mime_content_type( $file );
if( $mime[ 'type' ] )
$mimetype = $mime[ 'type' ];
else
$mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 );
header( 'Content-Type: ' . $mimetype ); // always send this
if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) )
header( 'Content-Length: ' . filesize( $file ) );
$last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) );
$etag = '"' . md5( $last_modified ) . '"';
header( "Last-Modified: $last_modified GMT" );
header( 'ETag: ' . $etag );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' );
// Support for Conditional GET
$client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) : false;
if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) )
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;
$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0;
// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);
if ( ( $client_last_modified && $client_etag )
? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) )
: ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) )
) {
status_header( 304 );
exit;
}
// If we made it this far, just serve the file
readfile( $file );
@whitenoise789
Copy link

whitenoise789 commented Sep 26, 2019

As an update, I was trying to add to this code to check if a user had certan capabiltities. However for the life of me I couldn't work out why I was getting no data for the user. It seems that the necessary files hadn't been called/created yet (I'm not an expert) so that's why I was getting blank/0. After doing much searching, I realised that changing the top part of the code to the below fixes this problem:

require_once('wp-blog-header.php');
wp_cookie_constants();
ob_end_clean();
ob_end_flush();

So I removed all the other requires, and replaced it with this one, which I think loads them anyway. Doing it the old way missed out an include which obviously dealt with the user. I could then use the user data how I wanted to check capabilities if(current_user_can('')).

Oh and where my manners - many thanks to Hakre for the this script to start with and for other users for their contributions.

@srcejon
Copy link

srcejon commented Nov 1, 2019

I find I need to call ob_start(); as originally suggested by @TIIUNDER for the CR fix, but appears to be missing from latter comments. Without this, when the WP Super Cache plugin is used, the MIME type is incorrect for some files (E.g. PDFs) and they are displayed as corrupted html instead of as a PDF.

ob_start();
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
wp_cookie_constants();
ob_get_clean();
ob_end_flush();

@ricks03
Copy link

ricks03 commented Jan 9, 2020

Comments from someone else who struggled to get this to work. If you want it to not require the file to exist at the location (should you have, for example, have your files stored outside of the Wordpress path), you can simply remove the check for the file's existence from .htaccess: RewriteCond %{REQUEST_FILENAME} -s

I too added the list of requires, but did not need the ob_* functions.

While there's a recommendation for using realpath() above, note it requires read permissions of the directory, which for me at least didn't work, where the original solution did:
$file = rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:'');

If you aren't using the uploads folder directly, you likely want:
RewriteRule ^wp-content/uploads/(secure/.*)$ dl-file.php?file=$1 [QSA,L]
instead of
RewriteRule ^wp-content/uploads/secure/(.*)$ dl-file.php?file=$1 [QSA,L]

If you want to check further that just logged in (say, if the user has certain permissions) you can modify:
if (strpos($file, $basedir) !== 0 ) {
to be
if (strpos($file, $basedir) !== 0 || current_user_can('user_capability_you care_about') == false ) {

For debugging, I found it useful to update the die statement(s) with the variables I cared about (not good for production)

$reports = current_user_can('user_capability_you care_about');
if ( !$basedir || !is_file($file)) {
    status_header(404);
    die("404 &#8212; File not found. basedir: $basedir   file: $file reports: $reports");
}

With that, it's working. There's still some quirks to be found, but it's working for me.

All that being said, this is an incredible solution, one which I've been trying to resolve with file manager plugins for a while.

The file manager plugins tend to fail in one of two ways:
You've kept your files in the wordpress path, so a URL directly to the file still works even though you're using a file manager plugin
or
You move the files out of the wordpress path (for security), at which point in time URLs to the files no longer work (no surprise, that's the point of moving them), but there's no process inside the file manager to let you create a link to the file that is role/security - aware.

@vpjm
Copy link

vpjm commented Jan 21, 2020

It doesn't work for me. I don't know if it's because the site I'm working on has its WordPress files in a subdirectory, because we are running WP Super Cache plugin, or some other cause. I scanned through all the comments here but it didn't seem like anyone was reporting a similar situation. Does anyone have this working in a situation where their WordPress files are in a subdirectory but the site runs from the root?

@ricks03
Copy link

ricks03 commented Jan 21, 2020

It would just require adjusting your .htaccess file and this line:
$file = rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:'');
I think.

this file is using the "true" path of the files, so where they are shouldn't matter.

@lamb73
Copy link

lamb73 commented Jan 29, 2020

I cannot seem to get this working whatsoever, and I have tried all suggestions in the comments, including copying and pasting others' working examples.

Am I doing this right?

  • PHP file in root directory (so alongside wp-config.php)
  • Ensure PHP filename matches that noted in the htaccess file
  • Ensure path to what you want to protect is correct in both the htaccess and PHP files
  • Load image directly in browser while logged out of WP, e.g. www.domain.com/wp-content/uploads/2020/01/image.jpg

@slehcimnad
Copy link

I don't want users to get redirected to the home page but to the 404 page. So, I've change that and it works fine in Firefox and even IE but it starts downloading 404.html in Chrome and Edge. Any ideas? My code:

$url = site_url().'/404';

//define users who have acces to the folder specified in htaccess
is_user_logged_in() || wp_redirect($url);

@tomas-eklund
Copy link

@stewartadam wrote

if (strpos($file, $basedir) !== 0) {
    status_header(403);
    die('403 &#8212; Access denied.');
}

The above code does not work on Windows where $basedir might be something like c:\wwwroot\wp-content/uploads and $file might be c:/wwwroot/wp-content/uploads/file.pdf. Notice how there's a mix of slashes and backslashes.

Copy link

ghost commented Apr 27, 2020

Hi @hakre this is brilliant!

Works for me in the remote host.

Is there any way to make this script work with this Wordpress plugin?

https://github.com/benhuson/password-protected

Entering the correct password in the password-protected home page doesn't count for this script as a logged-in user.

Many thanks!

@tdougla
Copy link

tdougla commented Jul 21, 2020

doesn't look like this thread is monitored by original author @hakre. I'm wondering if anyone has modified this script to only allow the author of the file to view the file, and any other user would be denied ?
thanks.

@rtpHarry
Copy link

@m1n1c
Copy link

m1n1c commented Feb 21, 2021

In a docker Wordpress nginx setup I ran into the issue, that pdf-viewer / pdf-embedder plugins would just show an error message about unavailable PDF resources.

Problem: In success case no status header code 200 was sent. I just added status_header(200); at the top of the good case part.
Also, I added NextGEN Gallery support (using wp-content/gallery instead of wp-content/upload folder). A rewrite rule had to be added in my nginx configuration too.

my dl-file.php version:

<?php
/*
 * dl-file.php
 *
 * Protect uploaded files with login.
 *
 * @link http://wordpress.stackexchange.com/questions/37144/protect-wordpress-uploads-if-user-is-not-logged-in
 *
 * @author hakre <http://hakre.wordpress.com/>
 * @license GPL-3.0+
 * @registry SPDX
 */

require_once('wp-blog-header.php');
wp_cookie_constants();
ob_end_clean();
ob_end_flush();

is_user_logged_in() || auth_redirect();

list($basedir) = array_values(array_intersect_key(wp_upload_dir(), array('basedir' => 1)))+array(NULL);

$file =  rtrim(isset($_GET[ 'g' ])?dirname($basedir).'/gallery/':$basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:'');

if (!$basedir || !is_file($file)) {
    status_header(404);
    wp_redirect(home_url());
    exit();
}

$mime = wp_check_filetype($file);
if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) )
    $mime[ 'type' ] = mime_content_type( $file );

if( $mime[ 'type' ] )
    $mimetype = $mime[ 'type' ];
else
    $mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 );

status_header(200);
header( 'Content-Type: ' . $mimetype ); // always send this
if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) )
        header( 'Content-Length: ' . filesize( $file ) );

$last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) );
$etag = '"' . md5( $last_modified ) . '"';
header( "Last-Modified: $last_modified GMT" );
header( 'ETag: ' . $etag );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 1800 ) . ' GMT' );

// Support for Conditional GET
$client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) : false;

if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) )
        $_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;

$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0;

// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);

if ( ( $client_last_modified && $client_etag )
        ? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) )
        : ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) )
        ) {
        status_header( 304 );
        exit;
}

// If we made it this far, just serve the file
readfile( $file );

my nginx config part:

# redirect all access to uploads and files directory through access checking script
# in order to only grant logged in users access to privacy concerned media.
# Exclude media starting with "public" in filename
location ~* /wp-content/(?:uploads|gallery)/(?!.*public) {
  rewrite /wp-content/uploads/(.*)$ $scheme://$host/dl-file.php?file=$1 last;
  rewrite /wp-content/gallery/(.*)$ $scheme://$host/dl-file.php?g=1&file=$1 last;
}                                                                                

@jmeile
Copy link

jmeile commented May 21, 2021

First of all, I want to thank the original @hakre and the contributors. I made the script working with some purposed fixes on 2021 and WP 5.7.2 and only one site; however, the code has also a purposed fix for multi-site. I also added a way of supporting rules for allowing specific users or roles.

Here my code for the interested:

  • dl-file.php
<?php
/*
 * dl-file.php
 *
 * Protect uploaded files with login.
 *
 * @link http://wordpress.stackexchange.com/questions/37144/protect-wordpress-uploads-if-user-is-not-logged-in
 * @link https://gist.github.com/hakre/1552239
 *
 * @author hakre <http://hakre.wordpress.com/>
 * @license GPL-3.0+
 * @registry SPDX
 *
 * Includes fixes proposed here:
 * https://gist.github.com/hakre/1552239#gistcomment-1439472
 *
 * And here:
 * https://gist.github.com/hakre/1552239#gistcomment-1851131
 * https://gist.github.com/austinginder/927cbc11ca394e713430e41c2dd4a27d
 *
 * And here:
 * https://gist.github.com/hakre/1552239#gistcomment-2735755
 *
 * .htaccess similar to this one:
 * https://gist.github.com/hakre/1552239#gistcomment-1313010
 *
 */

//Fix to allow for large files without exhausting PHP memory:
//https://gist.github.com/hakre/1552239#gistcomment-1851131
//https://gist.github.com/austinginder/927cbc11ca394e713430e41c2dd4a27d
if (ob_get_level()) {
    ob_end_clean();
}

//Fix proposed here
//https://gist.github.com/hakre/1552239#gistcomment-1439472
ob_start();
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
wp_cookie_constants();
ob_get_clean();
ob_end_flush();

//Added is_user_member_of_blog as the multi-site fix recomended it
is_user_member_of_blog() && is_user_logged_in() || auth_redirect();

//Allowed users and roles to access protected folders.
//The main key always represent a subfolder of wp-content/uploads. Please note
//that the key: 'default' represent the folder: wp-content/uploads.
//You can set here the allowed users and roles for each folder. Please note that
//the 'administrator' role will be always allowed to access all the files
//Please also note that at this point, all users are already authenticated because
//they passed the cointraint:
//is_user_member_of_blog() && is_user_logged_in() || auth_redirect();
//So, if you want to say that all roles are allowed to access the website, then
//add the 'all' role.
$folder_permissions['default'       ]['roles'] = array('all');
//$folder_permissions['ultimatemember']['users'] = array('my_user');
$folder_permissions['ultimatemember']['roles'] = array('subscriber', 'editor', 'contributor', 'autor');

list($basedir) = array_values(array_intersect_key(wp_upload_dir(), array('basedir' => 1)))+array(NULL);

//Fix for Multisite:
//https://gist.github.com/hakre/1552239#gistcomment-2735755
// Get the last occurence of the /sites/ part of the url
$sitepos = strrpos( $basedir, '/sites/' );
// Make sure the /sites/{int} is there
if ( $sitepos !== false ) {
        // Remove the /sites/{int}
        $basedir = preg_replace( '~\/sites\/\d+$~', '', $basedir );
}

$file =  isset( $_GET['file'] ) ? $_GET['file'] : '';
$file_root_folder = substr($file, 0, strpos($file, '/'));
if (!array_key_exists($file_root_folder, $folder_permissions)) {
  //This means it is either the uploads folder or any other subfolder not listed
  //here, the default will be assumed
  $file_root_folder = 'default';
}

$folder_permission = $folder_permissions[$file_root_folder];
$folder_users = array_key_exists('users', $folder_permission) ?
                $folder_permission['users'] : array();
$folder_roles = array_key_exists('roles', $folder_permission) ?
                $folder_permission['roles'] : array();

$auth_user = wp_get_current_user();
$auth_user_login = $auth_user->user_login;
$auth_user_role = $auth_user->roles[0];

$is_user_allowed = in_array($auth_user_login, $folder_users);
$is_role_allowed = ($auth_user_role == 'administrator') ||
                   in_array($auth_user_role, $folder_roles) ||
                   in_array('all', $folder_roles);

if (!$is_user_allowed && !$is_role_allowed) {
  status_header(403);
  die('403 &#8212; Access denied.');
}

$file = rtrim( $basedir, '/' ) . '/' . ( isset( $_GET['file'] ) ? $_GET['file'] : '' );
$file = realpath($file);

if ($file === FALSE || !$basedir || !is_file($file)) {
    status_header(404);
    die('404 &#8212; File not found.');
}

if (strpos($file, $basedir) !== 0) {
    status_header(403);
    die('403 &#8212; Access denied.');
}

$mime = wp_check_filetype($file);
if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) )
        $mime[ 'type' ] = mime_content_type( $file );

if( $mime[ 'type' ] )
        $mimetype = $mime[ 'type' ];
else
        $mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 );

header( 'Content-Type: ' . $mimetype ); // always send this
if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) )
        header( 'Content-Length: ' . filesize( $file ) );

$last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) );
$etag = '"' . md5( $last_modified ) . '"';
header( "Last-Modified: $last_modified GMT" );
header( 'ETag: ' . $etag );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' );

// Support for Conditional GET
$client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) : false;

if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) )
        $_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;

$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0;

// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);

if ( ( $client_last_modified && $client_etag )
        ? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) )
        : ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) )
        ) {
        status_header( 304 );
        exit;
}

// If we made it this far, just serve the file
readfile( $file );
  • Now the relevant parts of my .htaccess
# BEGIN DL-FILE.PHP ADDITION
RewriteCond %{REQUEST_FILENAME} -s
#Protecs only wp-content/uploads/ultimatemember. Add more RewriteRules as needed
RewriteRule ^wp-content/uploads/(ultimatemember/.*)$ dl-file.php?file=$1 [QSA,L]
#Protect all inside wp-content/uploads, comment it out if your website is fully private
#Please note that the order matters, so, that's why the previous rewrite must go before
#RewriteRule ^wp-content/uploads/(.*)$ dl-file.php?file=$1 [QSA,L]
# END DL-FILE.PHP ADDITION

I'm protecting only a subfolder: wp-content/uploads/ultimatemember, so, if you need it for another folder, then change that section. If you need it for the whole uploads folder, then uncomment the top line and drop the one with ultimatemember.

Best regards
Josef

@meow231a
Copy link

meow231a commented May 24, 2021

I've tried everything here and still can't get it to work. The closest I've gotten is with the version provided by @jmeile

The problem I am facing with this version now is that logged in as an administrator on a regular (single site) install of the latest WP, it gives me a 403 if I try to access the file. I uncommented the rewrite rule for all uploads, but haven't changed anything else. Any help would be greatly appreciated. What is it that I'm missing?

@jmeile
Copy link

jmeile commented May 27, 2021

Hi @meow231a

Could you post the following:

  • .htaccess -> It must be located under your WordPress root folder. You may hide sensitive date, eg: your ip address and website.
  • The value of $folder_permissions inside the file: dl-file.php. You need to set this according to your needs.
  • The roles that you want to access the files
  • The folders that you want to protect: on my case, I only want to protect everything inside: wp-content/uploads/ultimatemember. If you want to protect everything, then your folder would be: wp-content/uploads

You can also debug the problem as follows:

  • Put this on your wp-config.php file:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

This will create the file: wp-content/degub.log. In order to see some debug, just add lines like these on the dl-file.php:

error_log("Before doing checks");
error_log("After doing checks");
error_log("auth_user_login: " . $auth_user_login);
error_log("auth_user_role: " . $auth_user_role);
//For a complex variable
error_log("folder_permissions: " . var_export($folder_permissions, 1));
error_log("is_user_allowed" . var_export($is_user_allowed, 1));
error_log("is_role_allowed: " . var_export($is_role_allowed, 1));

Just put them in the code at the proper places. Then you can just check the output of debug.log:
tail -f wp-content/debug.log

Put this on your Apache VirtualHost:
LogLevel alert rewrite:trace3

And then restart Apache and check for the error log:
tail -f /var/log/apache2/error.log | fgrep '[rewrite:' | grep 'dl\-file'

This will show you if the RewriteRule on your .htaccess is been applied.

You may also post the outputs of the tail commands. In order to make them short, paste only the link of an image that must be protected on the browser, then watch the output.

Anyway, this is the dl-file.php that I used for debugging:

<?php
/*
 * dl-file.php
 *
 * Protect uploaded files with login.
 *
 * @link http://wordpress.stackexchange.com/questions/37144/protect-wordpress-uploads-if-user-is-not-logged-in
 * @link https://gist.github.com/hakre/1552239
 *
 * @author hakre <http://hakre.wordpress.com/>
 * @license GPL-3.0+
 * @registry SPDX
 *
 * Includes fixes proposed here:
 * https://gist.github.com/hakre/1552239#gistcomment-1439472
 *
 * And here:
 * https://gist.github.com/hakre/1552239#gistcomment-1851131
 * https://gist.github.com/austinginder/927cbc11ca394e713430e41c2dd4a27d
 *
 * And here:
 * https://gist.github.com/hakre/1552239#gistcomment-2735755
 *
 * .htaccess similar to this one:
 * https://gist.github.com/hakre/1552239#gistcomment-1313010
 *
 */

//Fix to allow for large files without exhausting PHP memory:
//https://gist.github.com/hakre/1552239#gistcomment-1851131
//https://gist.github.com/austinginder/927cbc11ca394e713430e41c2dd4a27d
if (ob_get_level()) {
  ob_end_clean();
}

//Fix proposed here
//https://gist.github.com/hakre/1552239#gistcomment-1439472
ob_start();
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
wp_cookie_constants();
ob_get_clean();
ob_end_flush();

error_log("Before doing checks");
//Added is_user_member_of_blog as the multi-site fix recomended it
is_user_member_of_blog() && is_user_logged_in() || auth_redirect();
error_log("User is authenticated");

//Allowed users and roles to access protected folders.
//The main key always represent a subfolder of wp-content/uploads. Please note
//that the key: 'default' represent the folder: wp-content/uploads.
//You can set here the allowed users and roles for each folder. Please note that
//the 'administrator' role will be always allowed to access all the files
//Please also note that at this point, all users are already authenticated because
//they passed the cointraint:
//is_user_member_of_blog() && is_user_logged_in() || auth_redirect();
//So, if you want to say that all roles are allowed to access the website, then
//add the 'all' role.
$folder_permissions['default'       ]['roles'] = array('all');
//$folder_permissions['ultimatemember']['users'] = array('my_user');
$folder_permissions['ultimatemember']['roles'] = array('subscriber', 'editor');
error_log("Folder permissions: " . var_export($folder_permissions, 1));

list($basedir) = array_values(
                   array_intersect_key(wp_upload_dir(), array('basedir' => 1))
                 ) + array(NULL);

//Fix for Multisite:
//https://gist.github.com/hakre/1552239#gistcomment-2735755
// Get the last occurence of the /sites/ part of the url
$sitepos = strrpos($basedir, '/sites/');
// Make sure the /sites/{int} is there
if ($sitepos !== false) {
  // Remove the /sites/{int}
  $basedir = preg_replace( '~\/sites\/\d+$~', '', $basedir );
  error_log("Multisite detected");
}
error_log("basedir: " . $basedir);

$file =  isset( $_GET['file'] ) ? $_GET['file'] : '';
error_log("file: " . $file);
$file_root_folder = substr($file, 0, strpos($file, '/'));
if (!array_key_exists($file_root_folder, $folder_permissions)) {
  //This means it is either the uploads folder or any other subfolder not listed
  //here, the default will be assumed
  $file_root_folder = 'default';
}
error_log("file_root_folder: " . $file_root_folder);

$folder_permission = $folder_permissions[$file_root_folder];
$folder_users = array_key_exists('users', $folder_permission) ?
                $folder_permission['users'] : array();
$folder_roles = array_key_exists('roles', $folder_permission) ?
                $folder_permission['roles'] : array();

error_log("folder_permission: " . var_export($folder_permission, 1));
error_log("folder_users: " . var_export($folder_users, 1));
error_log("folder_roles: " . var_export($folder_roles, 1));

$auth_user = wp_get_current_user();
$auth_user_login = $auth_user->user_login;
$auth_user_role = $auth_user->roles[0];

error_log("auth_user_login: " . $auth_user_login);
error_log("auth_user_role: " . $auth_user_role);

$is_user_allowed = in_array($auth_user_login, $folder_users);
$is_role_allowed = ($auth_user_role == 'administrator') ||
                   in_array($auth_user_role, $folder_roles) ||
                   in_array('all', $folder_roles);

error_log("is_user_allowed: " . var_export($is_user_allowed, 1));
error_log("is_role_allowed: " . var_export($is_role_allowed, 1));

if (!$is_user_allowed && !$is_role_allowed) {
  error_log("Issue 403, user doesn't have any permission");
  status_header(403);
  die('403 &#8212; Access denied.');
}

$file = rtrim($basedir, '/') . '/' .
        (isset( $_GET['file'] ) ? $_GET['file'] : '');
$file = realpath($file);
error_log("real path: " . $file);

if ($file === FALSE || !$basedir || !is_file($file)) {
  error_log("Issue 404");
  status_header(404);
  die('404 &#8212; File not found.');
}

if (strpos($file, $basedir) !== 0) {
  error_log("Issue 403");
  status_header(403);
  die('403 &#8212; Access denied.');
}

$mime = wp_check_filetype($file);
if(false === $mime[ 'type' ] && function_exists('mime_content_type'))
  $mime[ 'type' ] = mime_content_type( $file );

if ($mime['type'])
  $mimetype = $mime['type'];
else
  $mimetype = 'image/' . substr($file, strrpos($file, '.') + 1);

header( 'Content-Type: ' . $mimetype ); // always send this
if (false === strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS'))
  header('Content-Length: ' . filesize($file));

$last_modified = gmdate( 'D, d M Y H:i:s', filemtime($file));
$etag = '"' . md5($last_modified) . '"';
header("Last-Modified: $last_modified GMT");
header('ETag: ' . $etag);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 100000000) . ' GMT');

// Support for Conditional GET
$client_etag = isset($_SERVER['HTTP_IF_NONE_MATCH'])?
                 stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false;

if (! isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
  $_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;

$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified?
                               strtotime($client_last_modified) : 0;

// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);

if (($client_last_modified && $client_etag)?
       (($client_modified_timestamp >= $modified_timestamp) && ($client_etag == $etag))
     : (( $client_modified_timestamp >= $modified_timestamp) || ($client_etag == $etag))
   ) {
  error_log("Isue 304, got it from cache");
  status_header( 304 );
  exit;
}

error_log("Success, read file");
// If we made it this far, just serve the file
readfile( $file );

Best regards
Josef

@JPOak
Copy link

JPOak commented Jun 21, 2021

@jmeile Just want to say thanks for the consolidation you did it seems to be working well. I've actually had to use this for my design assets so that they are not public (header images, galleries). How much overhead do you think this ads to load times?

@jmeile
Copy link

jmeile commented Jun 22, 2021

@JPOak: This is difficult for me to say. I'm using it on a Website that doesn't have much users accessing it at the same time nor I have big images. On my case, I barely note a big delay. Anyway, I think there is one because php is anyhow reading the contents of the files on memory. I would say that the best is that you monitor the computer were the server runs and see how memory and CPU gets affected.

I really tried to do this with a different approach, but it didn't work. Here is what I did:

  1. WordPress set always a custom HTTP Header with the authenticated user through a hook. If none, then it was set to: "Anonymous"
  2. On my Apache VirtualHost, I cached that header and according to its value, I allowed or denied the request

It worked perfectly for php pages; however, the header wasn't set on media files, eg: .jpg, .gif, .pdf, etc.. The thing is that I didn't found were WordPress was handling this. I tried even several hooks and tried to look on the internet, but found no answer.

I would bet that an approach with Apache must be faster since media handling will be done the same way it is done by other requests.

Best regards
Josef

@JPOak
Copy link

JPOak commented Jun 22, 2021

@jmeile Thanks for your response. I guess I will just need to monitor. This gist seems to be the best discussion for this situation.

@jmeile
Copy link

jmeile commented Jun 23, 2021

@JPOak: You may look at this approach:
https://wordpress.stackexchange.com/questions/37144/how-to-protect-uploads-if-user-is-not-logged-in

See the answer by: bueltge: "2. Apache check for the Cookie". The good thing: it will be handled by Apache. The possible bad things:

  1. It depends on Cookies. I guess WP won't work without cookies. My major concern here would be security; a cookie can be faked, so, if a cookie with the name of: "wordpress_logged_in_xxxxxxx" is passed, the protected contents will be visible. I know that the "wordpress_logged_in" cookies have some kind of hash, but that answer there is not checking for that.
  2. It will only check whether or not the user is logged in, so, you won't actually see which WP role that user has. Perfect if you don't need roles.

It would be nice for instance if one could set two Http headers: current logged user and its WP role; however, as I said, I didn't find any hook where to do this for media files.

Best regards
Josef

@jmeile
Copy link

jmeile commented Jun 23, 2021

I just read a bit that StackExchange post where the original author of this Gist posted. He wrote:

Depending on how much traffic you have, it could be wise to better integrate this with your server, e.g. X-Accel-Redirect or X-Sendfile headers.

So, I found that there is a module that implements "X-Sendfile", which does what we need here: instead of handling the media files through php, they will be forwarded to Apache, which is more efficient.

The only problem: although that module works with Apache 2.4, it seems to be deprecated (or at least that's what people says). I found that this might be because it is not a standard module, it was designed initially for 2.2, and it hasn't been updated since long time ago; however, it seems that the last version, from March 2012, solved issues, which made it working for Apache 2.4; I installed that version and got it working.

Anyway, for the interested, here is how this is done:

  1. If you are using Ubuntu 20.x or any other Debian based distro, then install "apache2-dev" as follows:
apt install apache2-dev

This will give you access to the command: "apxs", which is used to compile and install the mod_xsendfile module. If you are using Windows or any other distro, then you will have to research how to install this by yourself. There are some Visual Studio and binary files here: https://github.com/nmaier/mod_xsendfile

  1. Now get the module file: "mod_xsendfile.c" from here: https://github.com/nmaier/mod_xsendfile
    The documentation can be read here: http://htmlpreview.github.io/?https://github.com/nmaier/mod_xsendfile/blob/master/docs/Readme.html

  2. Then install it by running:

apxs -cia mod_xsendfile.c
  1. Next, you need to tell Apache, which folders are allowed to use "X-SendFile". This must be done on your Apache VirtualHost, eg:
<VirtualHost *:443>
  ServerName your_domain.com

  ... Other directives come here

  XSendFilePath /var/www/html/your_wp_root/wp-content/uploads/sub_folder
  # Use this for protecting all WP uploads
  # XSendFilePath /var/www/html/your_wp_root/wp-content/uploads
</VirtualHost>

Please note that if "/var/www/html/your_wp_root" is a symlink, then you need to include the real path because php won't use the symlink.

  1. Then on the .htaccess file add:
# BEGIN DL-FILE.PHP ADDITION
# Enables XSendFile for dl-file.php
<Files dl-file.php>
  XSendFile on
</Files>
# The rest is equal to my previous post
RewriteCond %{REQUEST_FILENAME} -s
# Protecs only wp-content/uploads/sub_folder. Add more RewriteRules as needed
RewriteRule ^wp-content/uploads/(sub_folder/.*)$ dl-file.php?file=$1 [QSA,L]
# Protect all inside wp-content/uploads, comment it out if your website is fully private
# Please note that the order matters, so, that's why the previous rewrite must go before
# RewriteRule ^wp-content/uploads/(.*)$ dl-file.php?file=$1 [QSA,L]
# END DL-FILE.PHP ADDITION

The only difference on those lines and my previous code is that there you are enabling mod_xsendfile for dl-file.php.

  1. Then the updated dl-file.php:
<?php
/*
 * dl-file.php
 *
 * Protect uploaded files with login.
 *
 * @link http://wordpress.stackexchange.com/questions/37144/protect-wordpress-uploads-if-user-is-not-logged-in
 * @link https://gist.github.com/hakre/1552239
 *
 * @author hakre <http://hakre.wordpress.com/>
 * @license GPL-3.0+
 * @registry SPDX
 *
 * Includes fixes proposed here:
 * https://gist.github.com/hakre/1552239#gistcomment-1439472
 *
 * And here:
 * https://gist.github.com/hakre/1552239#gistcomment-1851131
 * https://gist.github.com/austinginder/927cbc11ca394e713430e41c2dd4a27d
 *
 * And here:
 * https://gist.github.com/hakre/1552239#gistcomment-2735755
 *
 * .htaccess similar to this one:
 * https://gist.github.com/hakre/1552239#gistcomment-1313010
 *
 */

//Fix to allow for large files without exhausting PHP memory:
//https://gist.github.com/hakre/1552239#gistcomment-1851131
//https://gist.github.com/austinginder/927cbc11ca394e713430e41c2dd4a27d
if (ob_get_level()) {
  ob_end_clean();
}

//Fix proposed here
//https://gist.github.com/hakre/1552239#gistcomment-1439472
ob_start();
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
wp_cookie_constants();
ob_get_clean();
ob_end_flush();

//Added is_user_member_of_blog as the multi-site fix recomended it
is_user_member_of_blog() && is_user_logged_in() || auth_redirect();

//Allowed users and roles to access protected folders.
//The main key always represent a subfolder of wp-content/uploads. Please note
//that the key: 'default' represent the folder: wp-content/uploads.
//You can set here the allowed users and roles for each folder. Please note that
//the 'administrator' role will be always allowed to access all the files
//Please also note that at this point, all users are already authenticated because
//they passed the cointraint:
//is_user_member_of_blog() && is_user_logged_in() || auth_redirect();
//So, if you want to say that all roles are allowed to access the website, then
//add the 'all' role.
$folder_permissions['default'       ]['roles'] = array('all');
//Replace "sub_folder" with the name of your folder
//$folder_permissions['sub_folder']['users'] = array('my_user');
$folder_permissions['sub_folder']['roles'] = array('subscriber', 'editor');

list($basedir) = array_values(
                   array_intersect_key(wp_upload_dir(), array('basedir' => 1))
                 ) + array(NULL);

//Fix for Multisite:
//https://gist.github.com/hakre/1552239#gistcomment-2735755
// Get the last occurence of the /sites/ part of the url
$sitepos = strrpos($basedir, '/sites/');
// Make sure the /sites/{int} is there
if ($sitepos !== false) {
  // Remove the /sites/{int}
  $basedir = preg_replace( '~\/sites\/\d+$~', '', $basedir );
}

$file =  isset( $_GET['file'] ) ? $_GET['file'] : '';
$file_root_folder = substr($file, 0, strpos($file, '/'));
if (!array_key_exists($file_root_folder, $folder_permissions)) {
  //This means it is either the uploads folder or any other subfolder not listed
  //here, the default will be assumed
  $file_root_folder = 'default';
}

$folder_permission = $folder_permissions[$file_root_folder];
$folder_users = array_key_exists('users', $folder_permission) ?
                $folder_permission['users'] : array();
$folder_roles = array_key_exists('roles', $folder_permission) ?
                $folder_permission['roles'] : array();

$auth_user = wp_get_current_user();
$auth_user_login = $auth_user->user_login;
$auth_user_role = $auth_user->roles[0];

$is_user_allowed = in_array($auth_user_login, $folder_users);
$is_role_allowed = ($auth_user_role == 'administrator') ||
                   in_array($auth_user_role, $folder_roles) ||
                   in_array('all', $folder_roles);

if (!$is_user_allowed && !$is_role_allowed) {
  status_header(403);
  die('403 &#8212; Access denied.');
}

$file = rtrim($basedir, '/') . '/' .
        (isset( $_GET['file'] ) ? $_GET['file'] : '');
$file = realpath($file);

if ($file === FALSE || !$basedir || !is_file($file)) {
  status_header(404);
  die('404 &#8212; File not found.');
}

if (strpos($file, $basedir) !== 0) {
  status_header(403);
  die('403 &#8212; Access denied.');
}

$mime = wp_check_filetype($file);
if(false === $mime[ 'type' ] && function_exists('mime_content_type'))
  $mime[ 'type' ] = mime_content_type( $file );

if ($mime['type'])
  $mimetype = $mime['type'];
else
  $mimetype = 'image/' . substr($file, strrpos($file, '.') + 1);

#X-SendFile will be enabled here
header("X-Sendfile: $file");

header( 'Content-Type: ' . $mimetype ); // always send this
if (false === strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS'))
  header('Content-Length: ' . filesize($file));

$last_modified = gmdate( 'D, d M Y H:i:s', filemtime($file));
$etag = '"' . md5($last_modified) . '"';
header("Last-Modified: $last_modified GMT");
header('ETag: ' . $etag);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 100000000) . ' GMT');

// Support for Conditional GET
$client_etag = isset($_SERVER['HTTP_IF_NONE_MATCH'])?
                 stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false;

if (! isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
  $_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;

$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified?
                               strtotime($client_last_modified) : 0;

// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);

if (($client_last_modified && $client_etag)?
       (($client_modified_timestamp >= $modified_timestamp) && ($client_etag == $etag))
     : (( $client_modified_timestamp >= $modified_timestamp) || ($client_etag == $etag))
   ) {
  status_header( 304 );
  exit;
}

So, the only two differences are:

  • The inclusion of:
header("X-Sendfile: $file");

to instruct apache to handle the media file

  • and the deletion of:
readfile( $file );

which is no longer necessary.

I guess this will make serving the files faster. You may try both and see if there is a difference.

And finally, I found that Apache 2.4 included the directive: "EnableSendfile"; however, I don't know how to use it. Perhaps you even don't need that old mod_xsendfile module.

Best regards
Josef

@JPOak
Copy link

JPOak commented Jun 23, 2021

@jmeile The Cookie method is much more straightforward. However, from what I understand is not very secure and easily hackable. People can correct me if I am wrong.

Thanks for your alternative method. I am concerned about speed. I noticed that my galleries are loading slower. Maybe it's just in my mind, but worth me checking into it. I would love to find a solution that is stable.

Thanks again.

@hakre
Copy link
Author

hakre commented Jul 12, 2021

@jmeile: Yes, this info is dated. Please see a PHP application's documentation that also has dedicated documentation (no idea if Wordpress fails the docs here, have not checked) https://www.dokuwiki.org/config:xsendfile . It falls into the domain of server configuration, therefore I would not expand on it. But I'm happy if you or others share in comments here.

@jmeile: Yes, it depends and the rule of thumb: Insecure. I would consider a specific cookie method also as server configuration and would not extensively comment on it myself here.

@Dalias96
Copy link

Thanks for this solution, its great!

I had to make changes in favor of supporting custom folder in wp-content/uploads dir

So, if you want to use subfolder, your .htaccess should look like this:

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

where subfolder stands for your custom folder.

Next, you should add variable on the very begining of dl-file:

$subfolder = 'subfolder/';

and then change line 20 (from original file, if you add var before, line number will change) to:

$file = rtrim($basedir,'/').'/'.$subfolder.''.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:'');

@dabock
Copy link

dabock commented Sep 28, 2021

Thanks for this solutions and all the contributions.
The (adapted) code still works.

If you have a ngnix + apacher server, you may need to do a ngnix redirect (instead of the .htaccess redirect).

For me, the following code made it work (I only restrict access to the folder /uploads/subfolder)

rewrite ^/wp-content/uploads/subfolder/(.*)$ /dl-file.php?file=$1 permanent;

@JPOak
Copy link

JPOak commented Sep 29, 2021

This is a great gist, which I have on follow. I am actually surprised that Direct Access Protection isn't discussed more in the Wordpress community. A lot of people mistake the many "Members Only" plugins providing this, but they do not. There is a third party service, but it is pretty expensive for smaller private sites.

I implemented this solution and it did work, but it slowed down certain aspects of the site. For example galleries loaded much slower and some images failed to be served. I turned off lazy load that did improve some things, but still not great.

@anthony-curtis
Copy link

anthony-curtis commented Sep 30, 2022

There were a few items needed to make this work on a shared hosting environment:

Make sure RewriteEngine On was at top of the .htaccess file, or somewhere before your htaccess changes like so:

RewriteEngine On

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

Disable any special CDN in your site tools or cPanel, and purge server cache between changes for sanity's sake.

Otherwise, the original htaccess and dl-file.php worked perfectly.

@Tsjippy
Copy link

Tsjippy commented Nov 3, 2022

I have no clue why this doesn't work:
.htaccess:

# BEGIN THIS DL-FILE.PHP ADDITION
RewriteEngine  on
RewriteRule ^wp-content/uploads/private/(.*)$ dl-file.php?file=$1 [QSA,L]
# END THIS DL-FILE.PHP ADDITION

Then the normal dl-file.php but with this on top:

<?php
 file_put_contents(__DIR__.'/dl-file.log', $_GET['file']."\n", FILE_APPEND);

This somehow only works for .jpe files. I tried a .jpg, .jpeg, .doc file and they are not triggered by the RewriteRule. Why?

@joelseneque
Copy link

I can't get this to work with my Wordpress site.
The redirect to Login works fine but when displaying the image it shows a blank file

@meelad2
Copy link

meelad2 commented Jun 20, 2023

I can't get this to work with my Wordpress site. The redirect to Login works fine but when displaying the image it shows a blank file

The problem was an unwanted blank line at the first of file.
Add these codes before the last line(67):

ob_clean();
flush();

Source: https://stackoverflow.com/a/8041597

@davidstaab
Copy link

I used this thread and a couple of other sources to implement a "media access control" solution for WordPress. My code draws on what I learned from this gist, so I want to share what I made. I'm a novice PHP developer and would love feedback and suggestions from this community! wp-mac, a Media Access Control solution for WordPress sites

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment