Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 );
@Gerkinfeltser

This comment has been minimized.

Copy link

commented Feb 27, 2012

This is exactly what I'd like to do with the contents of a WP upload folder on my site.
I stumbled on your solution at the wordpress.stackexchange.com but am unsure how to use the script.

You mention these two lines of code:

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

Are these lines added to a .htaccess file or somewhere else?
I apologize for this [most likely] basic question but am a php beginner.

Thanks!

@hakre

This comment has been minimized.

Copy link
Owner Author

commented Feb 27, 2012

Yes those Apache Directives belong into the .htaccess file of Wordpress, see as well Apache Module mod_rewrite­Docs and .htaccess Glossary Entry­Codex. You can leave comments and questions as well on How to Protect Uploads, if User is not Logged In? (Wordpress Answers).

@mrclaytorres

This comment has been minimized.

Copy link

commented Jun 29, 2012

Hello hakre,

I found this sulotion perfect for protecting the media files on Wordpress. I ran a membership Wordpress website. I tried this solution, but the thing is, the videos on my website's pages are not playing anymore. I embedded some premium .SWF files on my pages, and wanted to protect those .SWF files from direct URL access.

Can you please suggest some solution on this?

Thank you,

enes9

@hakre

This comment has been minimized.

Copy link
Owner Author

commented Jun 30, 2012

Hi @Enes9, this requires additional debugging. I assume this is related to headers being send in the request or the response. Also ensure that the flash plugin of your browser sends the needed cookies. You should be able to gather more information by tracking the network connections with Firebug in Firefox or a similar tool in the browser of your choice.

If you're looking for individual support, please leave an email address.

@lifepix

This comment has been minimized.

Copy link

commented Aug 25, 2012

Hi hakre,

Sorry for noob question, but how would this be modified to work on WP Multisite for all the subsites? So the user would have be a subscriber of the site (rather than the network preferably) to access the files.

I noticed that my multisite .htaccess file has these rewrite rules:

RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]

Thanks,
lifepix

@hakre

This comment has been minimized.

Copy link
Owner Author

commented Oct 12, 2012

Hi @lifepix, the solution has not been written for a multisite installation.

@beezwings

This comment has been minimized.

Copy link

commented Nov 16, 2012

Hi! Thanks for this. I'm a total noob and stumbled upon this. How would I change the .php file and .htaccess for the folder named, "work-files" which at the same level as "wp-content" (ie it's in the root folder). Also, can it work recursively through all the subfolders? Thanks!

@jorditost

This comment has been minimized.

Copy link

commented Feb 19, 2013

Hi! Thanks for this script! I have a basic (and silly) question, but which ist the better folder to place the script? I have placed it inside wp-content/uploads and I'm getting a 404 error (accessing a file directly from URL), as the file is seen as a post.

Another question: I want it just to check the uploads when accessing them by URL, but not the images attached to a post. How could I parse it? Thanks in advance!

@JeanLoureiro

This comment has been minimized.

Copy link

commented May 30, 2013

HI hakre,

I am trying to use your script on a subfolder inside uploads. at the moment it is '/wp-content/uploads/private/'.
The redirect script is working super well, but when I put the credentials it leads to a '404 - file not found.'

I have add 'private' in the code below, now it open the files, but you can access the file without be logged in.
$file = rtrim($basedir,'/').'/private/'.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:'');

Any suggestion?

Thanks a lot

@JeanLoureiro

This comment has been minimized.

Copy link

commented Jun 14, 2013

Ok guys,
apparently to achieve what I need, we have to change the 'structure' of the wordpress, so I gave up on it for time consuming issue and decided to create a folder called public and do the other way around, now I am facing another problem.
My images sitting on the uploads folder will not show if I am not logged in. How can I solve that?

Kind Regards

@hakre

This comment has been minimized.

Copy link
Owner Author

commented Jun 15, 2013

@Braus: I see no technical limitation with the private folder you aimed for first, just ensure all paths are correct and you shouldn't have any issues. Albeit I didn't test it, so let me know if you require additional support.

@jorditost: Your 404 issues needs troubleshooting and the feature request needs customization, Wordpress doesn't differ here between uploads, so one need to add this differentiation.

@beezwings: This should be merely a configuration setting, also as the traversal is by the file-system and supported from your OS, I don't see any recursion issues here. With a little modification of the Worpdress upload path configuration, I see no technical showstoppers to just do what you want to do.

@sogen

This comment has been minimized.

Copy link

commented Aug 23, 2013

1.- Hi, how do I use this?
2.- Where do I put it?
3.- Does it protect access to folders?

I can't get it to work just using:

/file.pdf

or

dl-file.php?file.pdf

Thanks.

@agskills

This comment has been minimized.

Copy link

commented Sep 25, 2013

Hi,

Can I change it to redirect to login page? With auth_redirect() it redirects to home page of the website. I tried to change it to

if (!is_user_logged_in())
{
wp_redirect( wp_login_url( site_url( '/login/ ' ) )); exit;
}

But that doesnt have any effect. It just redirects to same old home page. I am doing it right?

@sgissinger

This comment has been minimized.

Copy link

commented Oct 30, 2013

With WP 3.6.1 I added the following lines after require_once('wp-load.php'); otherwise is_user_logged_in() didn't work correctly in my case

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();
@stewartadam

This comment has been minimized.

Copy link

commented Feb 25, 2014

I would recommend changing the start of the script to this:

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();

is_user_logged_in() ||  auth_redirect();


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

$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.');
}

This includes the fix for Wordpress 3.6.1 mentioned above (thanks sgissinger!) as well as checks the true filesystem path of the file using realpath() in order to prevents directory traversal attacks. The unmodified script has a simpler version of this in place, but handles it via string replacement - realpath() ensures that any symbolic links and references are resolved first.

@christiansyl

This comment has been minimized.

Copy link

commented Mar 6, 2014

After a lot of painful hours I found out that the WP include (require_once('wp-load.php');) is adding a linefeed in the output. As a result binary files are seen as "corrupted", e.g. my png files starts with a linefeed.

I tried to use the PHP OB functions to trap this extra linefeed but it is not working, i.e. the linefeed is still there.

Anyone faced the same challenge in the past? Anyone with a potential solution?

Thanks,

Christian

@dsantuc

This comment has been minimized.

Copy link

commented Mar 20, 2014

How about adding an action hook after line 16 (e.g. "do_action('dl_file_before_download');", or somesuch) to allow plugins to register callbacks for authority checks?

@BrianKopp

This comment has been minimized.

Copy link

commented Oct 6, 2014

If you're a PHP/.htaccess noob like me, and you're trying to implement this, please read before attempting to implement. It may save you some head banging and throat punching...

  1. dl-file.php file goes in your public_html directory (the same place as your wp-config.php files and such)
  2. Add the additional lines posted by stewartadam for new version of WordPress in dl-file.php
  3. The .htaccess file you should be modifying is the one in the above directory.
  4. This solution locks EVERYTHING in your wp-content/uploads directory. This was the issue I was facing and was having misunderstandings with.

I'd imagine most people don't want their entire wp-content/uploads directory to be locked. Header images, images in public posts, etc. are all stored in this wp-content/uploads directory by default. If you're wanting to have a dedicated "membersonly" folder inside your wp-content/uploads directory, leaving alone existing content that you don't want to restrict, you'll have to make some modifications to your .htaccess file.

Here's my .htaccess:

# Use PHP5.4 as default
AddHandler application/x-httpd-php54 .php

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

# BEGIN THIS DL-FILE.PHP ADDITION
RewriteCond %{REQUEST_URI} ^.*wp-content/uploads/membersonly/.*
RewriteRule ^wp-content/uploads/(membersonly/.*)$ dl-file.php?file=$1 [QSA,L]
# END THIS DL-FILE.PHP ADDITION

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

# END WordPress

Options -Indexes

Notice:

  • Options -Indexes to prevent directory browsing.
  • The location is important here. It must come before the two lines of RewriteCond and one line of RewriteRule. These three lines send all file requests to index.php, which is not what we want. Putting THIS DL-FILE.PHP ADDITION before those three lines ensures dl-file.php is getting called when it should be.
  • In the RewriteRule ^wp-content/uploads/(membersonly/.*)$ line, it's important if you want a specific directory to be protected that you encapsulate it in parenthesis like that. What is in parenthesis gets sent to dl-file.php. This basically says, any calls to anything inside membersonly get sent to dl-file.php, with the 'file' variable being set to membersonly/SomeFile.

Hopefully this helps at least one person save a few unnecessary hours of anger and frustration...

@simonbernard

This comment has been minimized.

Copy link

commented Oct 8, 2014

Did anyone face the same problem as christiansyl? I'm facing the problem, that the image which is send by dl-file.php is somehow invalid and I can't find out the reason.

I can also see, that there is a newline which disapears if I comment the require_once('wp-load.php') line.

Any idea how this could be solved? I tried a ob_end_clean() just before the readfile() but it has no effect.

Thanks a lot!

@deas

This comment has been minimized.

Copy link

commented Oct 13, 2014

I am seeing the same thing @simonbernard

@deas

This comment has been minimized.

Copy link

commented Oct 13, 2014

For me, it was a closing ?> in wp-config.php. Removed it and now it works.

@youngmicroserf

This comment has been minimized.

Copy link

commented Oct 14, 2014

Hi -

I was wondering if anyone has tried this with a multisite installation since ms-files was removed. Previously, it was apparently sufficient to change ms-files.php so it wouldn't use SHORINIT and add the check. I wonder how to add the dl-file.php back to to rewrite rules given how the structure of the blog/files has changed since WP 3.5. Any pointers? Thanks!

@nilpix

This comment has been minimized.

Copy link

commented Dec 3, 2014

Thank you very much at all but more to @BrianKopp for 'noob's explaination'! :)

Only I have one problem. I had to comment de following:

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

Because although I was logged-in, the website throws me a "access denied".

Did I right? It works so far. :D

EDIT

IMPORTANT - WARNING:
Please, change: RewriteCond %{REQUEST_URI} ^.*wp-content/uploads/membersonly/.*
for: RewriteCond %{REQUEST_FILENAME} -s is there a security hole in first expression.

Question
Why can I do if I want to download too big files like 5-8GB? This PHP code throws me a 404 error :-|

@melissagillard

This comment has been minimized.

Copy link

commented Jan 22, 2015

I want to use this code to block access to a directory outside of my WordPress install. How do I modify the PHP file 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.

@hexagongirl

This comment has been minimized.

Copy link

commented Feb 26, 2015

I was also having the problem as @christiansyl and @simonbernard. I think I've solved it by using output buffering - as follows:

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();
$discard = ob_get_clean();

The other thing to note when testing this is that the browser will normally cache things - so clear history before testing each change.

@scot90

This comment has been minimized.

Copy link

commented Apr 14, 2015

I can't seem to get this to work. I would be happy just to restrict all access to wp-content/uploads/ --

I have the following code in my dl-file.php file, and it is in my public_html directory as suggested by @BrianKopp. Here is what my dl-file.php looks like:

1)))+array(NULL); $file = rtrim($basedir, '/') . '/' . (isset($_GET['file']) ? $_GET['file'] : ''); $file = realpath($file); if ($file === FALSE || !$basedir || !is_file($file)) { status_header(404); die('404 — File not found.'); } if (strpos($file, $basedir) !== 0) { status_header(403); die('403 — 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 ); --- My .htaccess file (the one that is also in my public_html directory): # BEGIN WordPress RewriteEngine On RewriteBase / RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} -s RewriteRule ^wp-content/uploads/(.*)$ dl-file.php?file=$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress --- Trying to follow along with @BrianKopp here...any insight would be really appreciated -- client is freaking out
@TIIUNDER

This comment has been minimized.

Copy link

commented Apr 23, 2015

I tried the fix by @hexagongirl, but it didn't work to me. I add to add an ob_end_flush and ob_end_clean, after that it works for me

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_end_clean();
ob_end_flush();
@cywebd

This comment has been minimized.

Copy link

commented Jun 25, 2015

What is the Nginx equivalent for the rules below?

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

This comment has been minimized.

Copy link

commented Aug 13, 2015

Seems like this thread is pretty old, but still chugging along. I was able to get this to mostly work using the dl-file.php text that scot90 posted. The issue I have, however, is that upon accessing a file from the protected folder, I'm logged out of the Wordpress site. So I get the file, but then I have to log back in again. Has anyone else seen this?

@JanikWeb

This comment has been minimized.

Copy link

commented May 24, 2016

Just follow @BrianKopp 's comment. This works perfectly. His solution also shows how to restrict access not to the whole /uploads/ dir but to a subdir.

@spktklr

This comment has been minimized.

Copy link

commented Jun 9, 2016

@cywebd & al. this will work for nginx:

location ~* /(?:uploads|files)/* {
    rewrite /wp-content/uploads/(.*)$ /dl-file.php?file=$1;
}
@idabrogie

This comment has been minimized.

Copy link

commented Jul 17, 2016

any solution to the problem that @simonbernad see?
I have no ?> in my config :/

@ahm-3d

This comment has been minimized.

Copy link

commented Jul 17, 2016

this worked for me...

in the .htaccess located in the root directory of my wordpress install:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# END WordPress

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

and then i added wp-private.php in the root directory of my wordpress install with the code below:


<?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' ])? '/private/'.$_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 );

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 );

@austinginder

This comment has been minimized.

Copy link

commented Aug 17, 2016

Discovered a php exhausted memory bug with this and serving large files. Adding the following block of code to the top of my file fixed it for me.

// Fix to allow for large file: http://stackoverflow.com/questions/6627952/why-does-readfile-exhaust-php-memory/38986798#38986798
if (ob_get_level()) {
    ob_end_clean();
}
@shaneg5525

This comment has been minimized.

Copy link

commented Dec 5, 2016

This doesnt seem to be working? if i sure to mysite.com/wp-content/uploads/private i'm re directed to the login... if i surf to a file within private im am able to access it and i'm not directed to login?

I've added this to my .htaccess in the root

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

and then added wp-private.php to my root with the following code

<?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' ])? '/private/'.$_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 );

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 );
@jonmspencer

This comment has been minimized.

Copy link

commented Apr 6, 2017

Nothing seems to be working here. Is this due to newer core updates? Working with WP 4.7.3.

@rbix1

This comment has been minimized.

Copy link

commented Apr 10, 2017

Fix for 4.7.3:
Then name of the map used in your directory mine is restricted

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

But ALSO in the dl-file.php :
$file = rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])? '/restricted/'.$_GET[ 'file' ]:'');

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_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($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])? '/**restricted**/'.$_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 );

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 );
@yodarub

This comment has been minimized.

Copy link

commented Apr 12, 2017

@rbix1, I copied your code and it redirects to frontpage after login? It also directs to frontpage when logged in and try to view the file in restricted folder.

@tameroski

This comment has been minimized.

Copy link

commented Aug 30, 2017

Guys, don't forget to add a rewrite base if you're working in a subdir. The whole rewrite rule should look like this :

<IfModule mod_rewrite.c>
RewriteBase /my/site/path/
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(restricted/.*)$ dl-file.php?file=$1 [QSA,L]
</IfModule>
@jirihon

This comment has been minimized.

Copy link

commented Sep 26, 2017

Hi,
the dl-file.php script blocks valid files with double dots to be downloaded. E.g. my-file..zip. At the line 20:

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

All double dots are stripped from the filepath, probably to prevent access to higher level folders by using the ../../ syntax. So why not to delete all occurances of ../ instead of ..?

@DigitalDesignerOnline

This comment has been minimized.

Copy link

commented Oct 25, 2017

how would this be modified to perform the same actions but within a folder outside the uploads folder. such as within a plugin folder? could I just replace the wp_upload_dir calls to wp_plugin_dir and my file path? thanks for the insight

@mcfarnell

This comment has been minimized.

Copy link

commented Dec 7, 2017

I am on a "nginx" server. Can someone tell me how to do the equivalent of the .htaccess code above on a nginx server? Thank you!

@BhargavBhandari90

This comment has been minimized.

Copy link

commented Jun 6, 2018

What if I don't want to restrict images? Other than images I want to block.

@Rsmith-gs

This comment has been minimized.

Copy link

commented Jul 20, 2018

This doesn't seem to be working for me. I'm still able to access the files I have uploaded via their url in a separate browser.

@digitalsmithy

This comment has been minimized.

Copy link

commented Aug 3, 2018

I wanted to protect media against all visitors, except those logged in, for a single directory in uploads.
If logged in - download the directly accessed file.
If not - redirect to homepage.
I'm no programmer - but I hacked a few ideas together and this simplified version worked for me. You don't need to modify the PHP for a different directory - just the HTACCESS.
I also found the above code simply served garbage - a screen full of nonsense which suggested the browser was trying to display a corrupt image (so probably missed the first bit of the file - or added one). The three " header('... " lines fixed this, as it tells the browser how to handle the file.
I also created an HTACCESS in /uploads/SOME_DIRECTORY to disable browsing (Options -Indexes).
Just for completeness I repeat - this is my version and I'm no pro, so it may not be 'right' in some strict sense. But it works.

HTACCESS

# block directory
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^.*wp-content/uploads/SOME_DIRECTORY/.*
RewriteRule ^wp-content/uploads/(SOME_DIRECTORY/.*)$ dl-file.php?file=$1 [QSA,L]
</IfModule>

dl-file.php contents

<?php
// Protect uploaded files with login.
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_end_clean();
ob_end_flush();

if ( is_user_logged_in() ) {
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' ]:'');
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file) . "\""); 
readfile($file);
}
else {
    wp_redirect( home_url(), 301 );
    exit;
}
@chrismheath

This comment has been minimized.

Copy link

commented Oct 18, 2018

I had a site which started as a regular WP, which then turned into a multisite. I've managed to get the latest version of the script working.

There were two issues with the original working with multisites:

  1. Where the htaccess rule for accessing the dl-file.php went (as multisite added extra conditions and rules)
  2. The actual dl-file itself and working with multisite upload installation paths

.htaccess

The dl-file referencing code was moved in before the extra WordPress multisite code

<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteBase /
	RewriteRule ^index\.php$ - [L]

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

	# add a trailing slash to /wp-admin
	RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

	RewriteCond %{REQUEST_FILENAME} -f [OR]
	RewriteCond %{REQUEST_FILENAME} -d
	RewriteRule ^ - [L]
	RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
	RewriteRule ^(.*\.php)$ $1 [L]
	RewriteRule . index.php [L]
</IfModule>

dl-file.php

The main issue was that basedir was now using the multisite relative uploads path, so combined with the original $_GET file request, you'd see a duplicate in the url (eg uploads/sites/2/sites/2/2018/10/file.jpg). This now removes the extra /sites/{int}, as well as checking whether the current user is part of the current multisite. Just copy and replace everything in the original between the file comments/documentation and 404 check (if ( $file === FALSE || !$basedir || !is_file( $file ) ) {).

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();

is_user_member_of_blog() && is_user_logged_in() || auth_redirect();

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

// 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 = rtrim( $basedir, '/' ) . '/' . ( isset( $_GET['file'] ) ? $_GET['file'] : '' );
$file = realpath( $file );
@121940kz

This comment has been minimized.

Copy link

commented Feb 22, 2019

2019 and this still works great. Thank you @BrianKopp for your help and explanation above from many years ago. Still works!

@SteveHa2

This comment has been minimized.

Copy link

commented Apr 16, 2019

Also in 2019 but having some problems, the directory locks down and redirects to the dl-file but i cant log in. I ran a test by repalcing the dl-file with a very simple test script and it seems that after the rewrite the user never appears as logged in using is_user_logged_in().

Has anybody else seen anything like this?

@driv3r333

This comment has been minimized.

Copy link

commented Jun 26, 2019

This works great if you want to restrict downloading of files.

I have a subfolder inside the uploads folder which has html and pdf files.
I just want to restrict direct access of html or PDF files via url when users are not logged in.

When the users are logged in it prompts the user to download the html file instead of displaying on the screen.

Could someone please help me modify this code so that it just displays the html or pdf in the browser instead of prompting the user to download the files?

Thanks

@farhadmoradik

This comment has been minimized.

Copy link

commented Jul 12, 2019

SPECIAL THANKS to HAKRE for this great engineering and sharing. You are great!
Please help me here:line 16: is_user_logged_in() || auth_redirect();
So the files are visible to any logged in user. Can I change it to only file owner (post_author in wp_posts)?
Any thoughts on that please Hakre?
THANKS AGAIN for this sharing.

@browlry

This comment has been minimized.

Copy link

commented Jul 18, 2019

Thanks for sharing this, Hakre. It works great.

One possibly unexpected side effect is that it sets the cache time to 3 years in the future.

It took me a while to figure out why users couldn't see updates to PDF files. I finally realized it was because of the header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' ); row in this file, which is setting the cache expiration time to about 3 years in the future. I changed this to header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 1800 ) . ' GMT' ); for a cache time of 30 minutes, which is more reasonable for our purposes.

@kodiSPO

This comment has been minimized.

Copy link

commented Aug 27, 2019

It's August 27th 2019. WP Version 4.9.10

function_exists('is_user_logged_in') returns TRUE
BUT
is_user_logged_in() is always returning FALSE even when I'm logged in.

Any suggestions?

@whitenoise789

This comment has been minimized.

Copy link

commented Sep 25, 2019

I've just joined to say thanks to all the contributers in this thread.

I had a similar problem to one of the other posters in that when logged in, a request for the file was being redirected to the home page. After doing some very basic debugging I realised this line was the issue.

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

This line apparently was looking like this: /blah my site/wp-content/uploads/private/private/myfile.xls

So simple changing it back to what was suggested earlier in the thread:

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

Fixed the problem, and it now works fine. For reference my htaccess:

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

# BEGIN THIS DL-FILE.PHP ADDITION
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(private/.*)$ dl-file.php?file=$1 [QSA,L]

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

# END WordPress

Options -Indexes

And 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
 * 
 * @author hakre <http://hakre.wordpress.com/>
 * @license GPL-3.0+
 * @registry SPDX
 */
 
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_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($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 );

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 );

Hope this helps someone :)

@whitenoise789

This comment has been minimized.

Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.