title: Protect PDF docs from being directly accessed in URL
body: <p>I want to protect a pdf file from being directly linked but instead have my logged in users be able to access it.  I have a link which currently goes to a javascript function which posts a form:
       $('nameofdoc').setProperty('value',doc);
       document.getElementById('sendme').submit();</p>
  
  <p>where sendme is the name of the form and nameof doc the index of the document I want to display.</p>
  
  <p>This then goes to a php file:</p>
  
  <pre><code> $docpath = $holdingArray[0].$holdingArray[1];
  
   $file = $holdingArray[0]; //file name
   $filename = $holdingArray[1]; //path to the file]
   header( 'Location:'.$docpath ) ;
   header('Content-type: application/pdf');
   header('Content-Disposition: attachment; filename="'.$filename  . '"');
   readfile($filename)
  </code></pre>
  
  <p>This all works fine it loads up the file and outputs the pdf.  What I can't do is protect the directory from direct linking - ie www.mydomain.com/pathToPdf/pdfname.pdf</p>
  
  <p>I've thought of using .htaccess to protect the directory but it's on a shared host so I'm not sure about the security and anyway when I've tried I can't get it to work.</p>
  
  <p>Any help would be great since this is my fourth day of trying to fix this.</p>
  
  <p>thanks</p>
  
  <p>Update</p>
  
  <p>I've had a lot of help thank you  but I'm not quite there yet.</p>
  
  <p>I've got an .htaccess file that now launches another php file when a pdf is requested from the directory:</p>
  
  <pre><code> RewriteEngine on
   RewriteRule ^(.*).(pdf)$ fileopen.php
  </code></pre>
  
  <p>When the fileopen.php file lauches it fails to open the pdf</p>
  
  <pre><code> $path = $_SERVER['REQUEST_URI'];
   $paths = explode('/', $path);
   $lastIndex = count($paths) - 1;
   $fileName = $paths[$lastIndex]; 
  
   $file = basename($path);
  
   $filepath = $path;
  
   if (file_exists($file)) {
       header( 'Location: http://www.mydomain.com'.$path ) ;
       header("Content-type: application/pdf");
       header("Content-Disposition: attachment; filename=".$file);
       readfile($filepath);
  
   }else{
       echo "file not found using path ".$path." and file is ".$file;
   }
  </code></pre>
  
  <p>The output is
  file not found using path /documents/6/Doc1.pdf and file is Doc1.pdf</p>
  
  <p>but the file does exist and is in that direcotry - any ideas??</p>
  
  <p>OKAY I'm happy to report that Jaroslav really helped me sort out the issue.  His method works well but it is tricky to get all the directory stuff lined up.  In the end I spent a few hours playing about with combinations to get it working but the principle he gave works well.  Thanks</p>