2

I have a PHP web application. I have built a function to download a PDF from an API end point like this:

public function importPdf($id)
{
    $resource = fopen('tmp/'.$id.'.pdf', 'w');

    $this->client->request('GET', $this->url . '/api/users/' . $id . '/pdf', [
        'headers' => [
            'Authorization' => "Bearer {$this->accessToken()}",
        ],
        'sink' => $resource,
    ]);
}

This is calling a Guzzle instance which is working fine and is saving the PDF file to my server. But what I need is for the PDF file to be downloaded to the users browser. If anyone could explain how this can be done I would be grateful.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Shaun
  • 526
  • 4
  • 13
  • Either you save it in a directory which is accessible by the web server, or you stream it giving an appropriate http header (which is, IMHO, a bit too broad to answer here). – Federico klez Culloca Jul 03 '18 at 15:20
  • Anyway, take a look [here](https://stackoverflow.com/questions/16847015/php-stream-remote-pdf-to-client-browser#16847068), it might help. – Federico klez Culloca Jul 03 '18 at 15:21

1 Answers1

2

Is this sort of what your looking for? I use this to allow users to download certain files from their browser.

public function functionNameHere($filename){
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    ob_clean();
    flush();
    readfile($filename); 
}
cvb
  • 723
  • 7
  • 21