BentCoder
BentCoder

Reputation: 12740

Either override behaviour of htaccess or a different solution for file access from URL

What it does?

  1. All requests to PDF files are redirected to validation.php by htaccess.
  2. validation.php takes the log.
  3. validation.php validates if user logged in or not.
  4. If not logged in then kick user out. If logged in then show PDF file.

Problem: Obviously 4th step (If logged in then show PDF file) fails because of the behaviour of htaccess.

Question: How can I solve this issue?

Thanks

HTACCESS:

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(pdf)$ [NC]
RewriteRule ^(.*)$ /validate.php?filename=$1 [L]

validation.php:

//STEP 1) Take a log
$file = 'log.txt';
$current = file_get_contents($file);
$current .= (isset($_GET['filename'])) ? $_GET['filename'] : '?';
$current .= " --- " . date('H:i:s') . "\n";
file_put_contents($file, $current);


//STEP 2) Authenticate login
session_start();

if (! isset($_SESSION['user']))
{
    session_write_close();
    header ('Location: /login.php');
    exit();
}
else
{
    //User should be eble to see the PDF file now.
}

Upvotes: 1

Views: 33

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

In the //User should be eble to see the PDF file now. step, instead of redirecting the user to the pdf file, simply output the file. So something like:

$file = $_GET['filename'];
$filename = basename($file);

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

@readfile($file);

Upvotes: 2

Related Questions