I have built a functionality on my website where I only want to allow certain people to be able to download or access certain pdfs from my uploads folder.
Searching aroud the internet and SO, I found a lot of answers and got really close in solving my problems.
The way I have structured my pdf is inside.
[root]/wp-content/uploads/scopes/unlocked-scopes/<filename>.pdf
I am interested in routing all the request for these files through a PHP script which is as follows.
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'wp-load.php');
function manage_action()
{
$page = get_permalink( get_page_by_path( '404-not-found' ) );
if($page) {
wp_redirect( $page );
exit();
} else {
wp_redirect(home_url());
exit();
}
}
// Bail if request paramter doesn't exist.
if(!isset($_GET['request'])) {
manage_action();
}
// check if someone is logged in or not.
if( !(current_user_can('author') || current_user_can('administrator')) ) {
manage_action();
}
// Get Scope
$scope_exists = get_posts( array(
'post_type' => 'project_scope',
'p' => $_GET['request'],
'numberposts' => 1,
));
// Bail if scope doesn't exists.
if(empty($scope_exists)) {
manage_action();
}
$scope = $scope_exists[0];
$author = $scope->post_author;
$user = get_current_user_id();
if(!current_user_can('administrator') && ($user != $author)) {
manage_action();
}
$file = wp_upload_dir()['basedir'] .'/scopes/unlocked-scopes/'.$_GET["file"];
if(substr($file, -1) == '/') {
$file = substr($file, 0, -1);
}
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Initially I built this restriction on my Local machine with Laragon setup on my windows machine and using Apache server.
I added the following in my .htaccess files at the root.
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} (unlocked-scopes.*)
RewriteRule ^wp-content/uploads/scopes/unlocked-scopes/(.*)$ wp-content/uploads/dl-file.php?file=$1 [QSA,L]
</IfModule>
This works absolutely fine on apache local server, but my live server is using openlitespeed
server on a digital ocean droplet and it doesn't work there at all.
I have added this rule before the wordpress rule.
UPDATED
When I try to visit any pdf from unlocked-scopes
folder in my live server it opens without ever hitting my php script which makes it accessable publically. Is there something else that needs to be added when working with openlitespeed and .htaccess
?