How can I restrict only the PDF files that I uploaded through FTP, I copied the link of each PDF file and created buttons in WooCommerce, I can Restrict the Page/Post but not the PDF. I want users to login to be able to view the PDF files. I would appreciate the support.
1 Answer
You cannot restrict users from downloading a file from a path using a wordpress login for various reasons, the most important is that the WP login is handled by PHP while the download is handled via Apache.
That said, there is a way to achieve the result of what you’re after. What you need to do is write a custom download handler for your PDFs. There are various ways to do this, but they will resemble something like this.
function downloadPDF(){
if(!is_user_logged_in(){
//do your user isn't logged in logic here
}
else{
$path = WP_CONTENT_DIR . '/path/to/pdf'; //The path to the pdf file that you want to access.
if(file_exists($path)){ //check to make sure the file exists
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.end(explode("https://wordpress.stackexchange.com/",$path).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
exit();
}
else{
//do your invalid file logic here
}
}
}
What is happening here is, it checks to see if a user is logged in. If so, it checks to see if a file exists and if it does serve it for download.
Note, this is an extremely basic skeleton of what you need to do. You will need to make this function fire when someone attempts to download a pdf (possibly with an .htaccess rule + action hook, but there are other ways).