Jared Eitnier
Jared Eitnier

Reputation: 7152

php force download pdf from a dynamic link and store to local folder

I am building a script that imap's into a google mailbox, gets a message, and extracts a link from the body. The link, when opened via php, starts a download process of a PDF file from an external source.

Here is what I need to do:

  1. Programmatically open the link which initiates a download
  2. Download the PDF, bypassing any dialog boxes obviously
  3. Store the PDF file to a local folder on the web server

I have been successful up to the point where I can initiate the download process and download the file. However, every attempt at opening the PDF finds the file to be corrupted and I can't figure out why. Here's what I'm trying now. The following is based on similar topics.

    $filename =  http://cckk.ca/KE645R26/geico.com_SEO_Domain_Dashboard_20121101_00.pdf

    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filename));
    ob_clean();
    flush();
    readfile($filename);
    exit;

I am thinking that maybe there's an issue with the filename I'm passing?

Note: This script will be setup as a CRON task that is run on the server every few seconds, in order to constantly fetch from OUR own mailbox, so this is not going to have any type of user interaction or be a security risk to a user.

Upvotes: 1

Views: 3719

Answers (2)

iambriansreed
iambriansreed

Reputation: 22241

Try:

$filename = 'http://cckk.ca/KE645R26/geico.com_SEO_Domain_Dashboard_20121101_00.pdf';

file_put_contents(
    '/your/server/path/folder/' . basename($filename), // where to save file
    file_get_contents($filename)
);

exit;

Upvotes: 5

Trenton
Trenton

Reputation: 1458

You cannot use filesize() on remote files. Most likely, the errors from that call are showing up at the beginning of the file and thus corrupting it.

Upvotes: 2

Related Questions