Wordpress Deny Access to Uploads for Non Logged in Users

Protecting WordPress Media Uploads Unless User is Logged In

null

Sometimes developing even the nigh simplistic solutions can exist difficult. We take worked with several clients that have requested to continue their uploads folder individual. While in that location are some plugin solutions that may help in this – I figured I would post a simplistic way to practice this manually to keep your lawmaking clean.

How does information technology work?
We will be modifying the .htaccess file in the root of your WordPress directory and telling it to redirect uploaded files if a user is non logged in. We volition also add a redirect parameter to tell WordPress how to handle users so they will be correctly redirected to the file after logging in.
**Notation: If y'all are using a custom plugin for front-end login screens (such as Profile Architect) yous will need to modify the code a scrap to pass a redirect parameter to that login screen, but this should give you a good start. **

WordPress and .HTACCESS
WordPress will generate an .htaccess file when y'all change your permalink construction. Because of this behavior, we need to make certain that we understand how to input custom htaccess rules in the file then that WordPress volition not overwrite them when changing this structure. Let's go into the code.
**Notation: This tutorial assumes that you keep all your uploads in the aforementioned binder past unchecking "Organize my uploads into month- and year-based folders". **

The code
Navigate to your .htaccess file via FTP in your WordPress root. If you lot do not meet one – login to WordPress and update your permalink structure (Settings -> Permalinks -> Choose Post name). At present that you have an .htaccess file, edit it. We will exist adding this code to our .htaccess file:

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

Make sure to add the code above the generated lawmaking that WordPress uses below (annihilation outside this WordPress will not touch).

# Begin WordPress

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# End WordPress

Okay, now what?
Now we have command – nosotros can do anything we want when an uploaded file is accessed. Each time an uploaded file is accessed nosotros are telling it to run lawmaking nosotros will create in a file named "dl-file.php". Create a file named "dl-file.php" (without the quotes) in the root of your WordPress directory. Now, add this code inside the file to command our uploads:

require_once('wp-load.php');

If (!is_user_logged_in()){
$upload_dir = wp_upload_dir();
repeat $upload_dir['baseurl'] . '/' . $_GET[ 'file' ];
wp_redirect( wp_login_url( $upload_dir['baseurl'] . '/' . $_GET[ 'file' ]));
exit();
}
list($basedir) = array_values(array_intersect_key(wp_upload_dir(), array('basedir' => one)))+array(NULL);

$file = rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])?$_GET[ 'file' ]:'');
if (!$basedir || !is_file($file)) {
status_header(404);
dice('404 — File not found.');
}

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

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

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 One thousand Y H:i:s', filemtime( $file ) );
$etag = '"' . md5( $last_modified ) . '"';
header( "Last-Modified: $last_modified GMT" );
header( 'ETag: ' . $etag );
header( 'Expires: ' . gmdate( 'D, d Chiliad Y H:i:due south', time() + 100000000 ) . ' GMT' );

// Back up for Conditional Get
$client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) : imitation;

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

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

// Make a timestamp for our about contempo 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 );

What exactly did nosotros only do?
The showtime line of lawmaking

require_once('wp-load.php');

is just telling the PHP file to load the necessary files to phone call WordPress functions.

The next little snippet is the fundamental:

If (!is_user_logged_in()){
$upload_dir = wp_upload_dir();
repeat $upload_dir['baseurl'] . '/' . $_GET[ 'file' ];
wp_redirect( wp_login_url( $upload_dir['baseurl'] . '/' . $_GET[ 'file' ]));
exit();
}

Nosotros are validating that the user is not logged in (if y'all have sure users yous need to restrict you lot can modify this). Since the user is not logged in, we will redirect the user to the login page. Once the user logs in, it will automatically redirect him/her to the file. Although some modifications were fabricated to the code, original credit goes tohttp://wordpress.stackexchange.com/questions/37144/protect-wordpress-uploads-if-user-is-not-logged-in.

Hope this helps!

Travis Hoglund
Zer0 to 5ive Senior Programmer

dialwelyine.blogspot.com

Source: https://0to5.com/protecting-wordpress-media-uploads-unless-user-is-logged-in/

0 Response to "Wordpress Deny Access to Uploads for Non Logged in Users"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel