Mike Dias
Mike Dias

Reputation: 1

Open/save PDF located in server folder

I want to give to the users of a PHP intranet the possibility to open/save PDF files, which are located in a folder on the Apache server. The PDFs have company private information, so I don't want to put them in a web folder.

echo '<form name="openpdf" method="POST" action="downloadPDF.php">';
echo '<input type="hidden" name="pdf">';
echo'</form>';

<tr>
<td> PDFFile1 </td>
<td><a href=javascript:void(null); onclick='document.openpdf.pdf.value="c:\pdfs\example.pdf";document.openpdf.submit(); return false;'><IMG src="img/pdf.jpg"></a></td></tr>

downloadPDF.php:

<?
$pdf=$_POST["pdf"];
if (file_exists($pdf)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');   
    header('Content-Disposition: attachment; filename='.basename($pdf));   
    header('Content-Transfer-Encoding: binary');     
    header('Expires: 0');    
    header('Cache-Control: must-revalidate');   
    header('Pragma: public');   
    header('Content-Length: ' . filesize($pdf));     
    ob_clean();     
    flush();     
    readfile($pdf);     
    exit; 
} 
?>

The problem is when the user open/save a file, the path is pointing for that folder but in the client PC and not at the server.

Upvotes: 0

Views: 4053

Answers (3)

DavChana
DavChana

Reputation: 1976

What at the moment you are doing is that

  1. Javascript is putting a value of c:\pdfs\example.pdf in the pdf field of your form on click and submitting it to downloadpdf.php.
  2. On server, Downloadpdf.php is assigning $_POST["pdf"] value to $pdf.
  3. If file $pdf exists, it is simply proceeding to offer user to download this file.

Now, this may work where server & client is same computer(specifically on a PC, because of C: drive); i.e. like on Local XAMPP. But on real world, where user and server will be on totally different computers, the if (file_exists($pdf)) is always going to fail(unless On server's C: actually there is a file exaple.pdf in folder pdfs) In real world, step 3 will fail, because $pdf = c:\pdfs\example.pdf and server will look into its own C: drive (if it is a windows server).
You should

1 Try to upload file with an HTML File Upload Box.
2 Get/fetch it on server using $_FILES and do processing
3. Send required headers for downloading.

For further information, please see HTML Form File Upload (Google) & $_FILES (PHP.Net)

Upvotes: 0

M&#225;t&#233; Gelei
M&#225;t&#233; Gelei

Reputation: 869

If you process the PDFs internally on the server from PHP, you should omit the file:/// from the URL.

So it should be

$pdf="c:/pdfs/example.pdf";

Upvotes: 1

hakre
hakre

Reputation: 197692

The server does not know the client PC, so readfile does not work here.

You might want to try with a redirect, but I must admit I have no clue if browsers allow that for security reasons (you're switching protocols with the redirect).

Upvotes: 0

Related Questions