Question

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 http://localhost/pdf?

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");
Was it helpful?

Solution

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 file transfer and 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

OTHER TIPS

You can use output control functions. Place ob_start() at beginning of your script. At the end use ob_get_contents() and save the content to a local file.

After that you can use ob_end_clean() or ob_end_flush() depending on whether you want to output PDF to browser as well, or you would redirect user to some other page. If you use ob_end_flush() make sure you set the headers before flushing the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top