Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Wordpress login to download uploaded files

View dl-file.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
<?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 );

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!

Owner

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

enes9 commented

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

Owner
hakre commented

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.

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

Owner

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

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!

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!

Braus commented

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

Braus commented

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

Owner
hakre commented

@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.

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.

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?

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

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.

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

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?

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...

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!

I am seeing the same thing @simonbernard

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

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!

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 :-|

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.

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.

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:

<?php
/*

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 — 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

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.