Save PDF to local server

I create a PDF file from raw binary data and works fine, but because of the headers that I define in my PHP file, it prompts the user to either “save” the file or “open with”. Is there a way to save the file on a local server somewhere here http://localhost/pdf ?

Below are the headers I defined on 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"); 
+4
source share
2 answers

If you want to save the file on the server, rather than upload it to the visitor, you do not need headers. The headers are meant to tell the client that you are sending them, that in this case nothing (although you are probably showing a page linking to a recently created PDF file or something like that).

So, instead, just use a function like file_put_contents to store the file locally, ultimately letting your web server handle HTTP headers.

 // Let 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 
+7
source

You can use the output control functions. Put ob_start () at the beginning of your script. In the end, use ob_get_contents () and save the contents in a local file.

After that, you can use ob_end_clean () or ob_end_flush () depending on whether you want to output the PDF to the browser, or redirect the user to another page. If you use ob_end_flush (), make sure you set the headers before clearing the data.

0
source

Source: https://habr.com/ru/post/1396619/


All Articles