How to protect file if User not logged in WordPress

If User not logged In and try to download .PDF file or any other extension below code will protect file even if User try to download via direct link.

1. Add code in function.php or your plugin file. Update permalink after adding this code. This code will add htaccess rules in .htaccess file.

add_filter(‘mod_rewrite_rules’,’output_htaccess’);
function output_htaccess( $rules ){

$nrule = ‘RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteRule ^(.*)$ /wp-content/themes/theme-name/download.php?file=$1 [L]’;
$rules = str_replace(‘RewriteBase /’, $nrule , $rules);

return $rules;

}

2. Create new file with named download.php inside you theme folder and past below code.

require_once($_SERVER[‘DOCUMENT_ROOT’]. ‘/wp-load.php’);
if (!is_user_logged_in()) {
// redirect to login page or show the message + login form
die(‘Please login’); // or exit, wp_redirect etc
}

$filename = $_GET[“file”];
$filePath = $_SERVER[‘DOCUMENT_ROOT’]. “/”.$filename;
header(‘Content-type:application/pdf’);
header(‘Content-disposition: inline; filename=”‘.$filename.'”‘);
header(‘content-Transfer-Encoding:binary’);
header(‘Accept-Ranges:bytes’);
@ readfile($filePath);

Similar Posts

Leave a Reply

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