0

I made a very simple dashboard with HTML/PHP/JS (and a MySQL database) where some users (after a secure login with username and password) can access and insert some activities with details and attach a file in PDF format. My dashboard is in a directory like /var/www/my-dashboard and inside there is another directory with all the PDF file uploded by the users: /var/www/my-dashboard/files with a structure like this: /var/www/my-dashboard/files/file1.pdf /var/www/my-dashboard/files/file2.pdf /var/www/my-dashboard/files/file3.pdf

The users have to login to the dashboard to insert an activity and upload the PDF file so a non-registered user can't do this. The problem is that a non-registered user with a specific link can access the PDF files from the internet (with a link like this: http://[IP/DNS]/files/file1.pdf). I want to avoid this that these files can only be opened and viewed by the registered user. How can I implement this in PHP?

1 Answer 1

1

You can use PHP to display the PDFs.

Make sure to store your PDF files in a folder, which is not accessible via a direct HTTP request.

Example: Put it into /var/www/pdfs/ and reach the directory via PHP or block access to your specific folder in your Nginx or Apache2 configuration.

$file = 'file1.pdf';
  
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $file . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
  
@readfile($file);
9
  • Hi, thank you! Is there a way to do this with the .htaccess configuration?
    – ducarpit
    Commented Sep 7, 2022 at 13:28
  • Of course. Just like that in your folder with the PDFs should work: Order Allow,Deny Allow from all <Files ~ "\.(pdf)$"> Deny from all </Files>
    – Corsin1337
    Commented Sep 7, 2022 at 13:35
  • I tried it but it doesn't work :( ... maybe it is not the right syntax?
    – ducarpit
    Commented Sep 7, 2022 at 13:51
  • Do you use Apache2? If this doesn't work for you, try to add RedirectMatch 403 ^/folder/.+\.(pdf)$ in your Apache2 conf file and restart Apache2! Replace "folder" with your folder name that contains the PDF files in it.
    – Corsin1337
    Commented Sep 7, 2022 at 14:01
  • Yes, in this way it works but unfortunatly it blocks all the request (also the request from the dashboard).... i tried this: RewriteCond %{HTTP_REFERER} !^http?://192.168.1.69/.*\.php [NC] RewriteRule ^(folder/.*\.pdf|folder/.*\.jpg|folder/.*\.jpeg|folder/.*\.png)$ - [L,F,NC] it seems working, but maybe it isnt' the best solution...
    – ducarpit
    Commented Sep 7, 2022 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .