Hi we have a web application with document repository in php and web server is apache. How can I prevent access to these documents file directly using url, so that only our users can acceess the documents after login. The url for accessing the documents is also being displayed in google search result.
Don't store your files in your web root. Keep them outside of your web root and refer to them via a PHP file. That file will authenticate the user to verify that you want them to be able to download the file and allow them to see it. Otherwise it will prevent the from occurring or load an error message instead.
HTML:
<a href="download.php">Download</a>
Sample PHP (download.php):
<?php
if (!isset($_SESSION['authenticated']))
{
exit;
}
$file = '/path/to/file/outside/www/secret.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
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($file));
ob_clean();
flush();
readfile($file);
exit;
?>