Salman Salman - 1 year ago 91
PHP Question

Save pdf to local server

I am creating a PDF file from raw binary data and it's working perfectly but because of the headers that I define in my PHP file it prompts the user either to "save" the file or "open with". Is there any way that I can save the file on local server somewhere here


Below are the headers I have defined in my page

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Transfer-Encoding: binary");

Answer Source

If you would like to save the file on the server rather than have the visitor download it, you won't need the headers. Headers are for telling the client what you are sending them, which is in this case nothing (although you are likely displaying a page linking to you newly created PDF or something).

So, instead just use a function such as file_put_contents to store the file locally, eventually letting your web server handle transfer hand HTTP headers.

// Let's say you have a function `generate_pdf()` which creates the PDF,
// and a variable $pdf_data where the file contents are stored upon creation
$pdf_data = generate_pdf();

// And a path where the file will be created
$path = '/path/to/your/www/root/public_html/newly_created_file.pdf';

// Then just save it like this
file_put_contents( $path, $pdf_data );

// Proceed in whatever way suitable, giving the user feedback if needed 
// Eg. providing a download link to http://localhost/newly_created_file.pdf
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download