I've searched all over but many is similar to my case but didn't really help. So my website allows user to download PDF when they press the button but if they enter the URL like "test.com/ebook/good.pdf " it will redirect them to my directory and show them the PDF without them pressing the download button. So is there a way to prevent them from entering my ebook using some code instead of htaccess?
Asked
Active
Viewed 48 times
-4
-
The only way I believe you can prevent direct url access is with htaccess. [See here](https://stackoverflow.com/questions/9282124/deny-direct-access-to-a-folder-and-file-by-htaccess) – Hayden Passmore Oct 10 '17 at 02:48
1 Answers
0
Well, actually, you have to use both .htaccess and some code. If you're using PHP without an MVC framework like Lavarel or CodeIgniter, the simplest way would be to put a .htaccess file in your download folder that redirects all requests to files in the folder to an index.php
file, which will send headers that will force the user to download the file instead of opening it directly.
The code will look something like this:
<?php
$filename = basename($_SERVER['REQUEST_URI']);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename='" . $filename . "'");
header('Content-Transfer-Encoding: binary');
echo file_get_contents(__DIR__ . '/' . $filename);

John Doe
- 212
- 1
- 8