I've in the past protected PDFS when a user is not logged in using the following code :
RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
RewriteRule . - [R=403,L]
For some reason it quit working on me. Research has shown that maybe wordpress-logged_in is no longer relevant as it was a hacking hole. Is there an alternative solution for protecting PDF documents if a user is not logged in?
These pdfs are not embedded on a page rather "hot linked" if you will. I'm not looking for a bloated plugin. Just a solution to protect PDF's specifically.
Edit:
Below is my full htaccess.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /new/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /new/index.php [L]
</IfModule>
# END WordPress
RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteRule ^(.*)$ /wp-content/download-protect.php?file=$1 [L]
# disable directory browsing in WordPress
Options -Indexes
# protect wp-config.php
<files wp-config.php>
order allow,deny
deny from all
</files>
# Protect .htaccess
<files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</files>
This is a slightly heavier solution than yours, but IMHO it is still better than some 'Super Protect Your PDFs' Wordpress plugin
All you have to do is place download.php file somewhere in your WP installation (for example wp-content folder). Then you have to redirect all the requests to PDF files will be passed to download.php script. It includes some basic WP stuff so you can use WP functions, such as is_user_logged_in()
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^.*(pdf)$
RewriteRule ^(.*)$ /wp-content/download.php?file=$1 [L]
download.php
require_once('/path/to/wp-config.php');
require_once('/path/to/wp-includes/wp-db.php');
require_once('/path/to/wp-includes/pluggable.php');
if (!is_user_logged_in()) {
// redirect to login page or show the message + login form
die; // or exit, wp_redirect etc
}
header("Content-Type: application/octet-stream");
$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With