11/10/2015 - LINUX, PHP
The scenario is simple so you shouldn't be able to access a file via a HTTP request unless you're logged in otherwise you get redirected to main page. In this example, we're going to use a dummy PDF file but you can extend types as you wish.
Assuming that our URL is http://www.inanzzz.com/
.
http://www.inanzzz.com/1.pdf
..htaccess
picks up the request and forwards it to validate.php
.validate.php
checks if user was logged in or not.Change AllowOverride None
to AllowOverride All
in /etc/httpd/conf/httpd.conf
file then restart apache server.
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
AllowOverride All
RewriteEngine On
RewriteCond %{REQUEST_URI} \.(pdf)$ [NC]
RewriteRule ^ validate.php?request_url=%{REQUEST_URI} [L]
# To disable or prevent the directory access/listing
Options -Indexes
<?php
session_start();
if (!isset($_SESSION['login'])) {
header ('Location: index.php');
exit();
} else {
// Get server document root
$document_root = $_SERVER['DOCUMENT_ROOT'];
// Get request URL from .htaccess
$request_url = $_GET['request_url'];
// Get file name only
$filename = basename($request_url);
// Set headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename='.$filename);
// Output file content
@readfile($document_root.$request_url);
}
<h3>HTACCESS controlled site</h3>
<p>You should be logged in in order to access 1.pdf via URL.</p>
<?php
session_start();
echo !isset($_SESSION['login'])
? '<a href="?login">Click here to login</a>'
: '<a href="?logout">Click here to logout</a>';
if (isset($_GET['login'])) {
$_SESSION['login'] = true;
header('location: index.php');
exit;
} elseif (isset($_GET['logout']) && isset($_SESSION['login'])) {
unset($_SESSION['login']);
session_destroy();
header('location: index.php');
exit;
}
// Do something else here if you want
project-folder
.htaccess
1.pdf
index.php
validate.php
Access to http://www.inanzzz.com/
and click "Login" link. Try to access http://www.inanzzz.com/1.pdf
which will successfully let you see the file content. Go back and click "Logout" link. Try to access http://www.inanzzz.com/1.pdf
but in this case you'll be redirected to home page instead.