0

I want to download a pdf file from a server to my local device. I used the following code:

$url="https://www.example.com/test.pdf";
    $file = fopen(dirname(__FILE__) ."/PDF Files/".$filename, 'w+');
    $curl = curl_init($url);
    curl_setopt_array($curl, [
                                CURLOPT_URL            => $url,
                                CURLOPT_BINARYTRANSFER => 1, // No effect from PHP 5.1.3
                                CURLOPT_RETURNTRANSFER => 1,
                                CURLOPT_FILE           => $file,
                                CURLOPT_TIMEOUT        => 50,
                                CURLOPT_USERAGENT      => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                                ]);
    $response = curl_exec($curl);

after running the code, I find the PDF file on my local device but when I open it, i get a message saying that the file is corrupted. Any help?

Nour
  • 11
  • 1
  • 1

1 Answers1

-1

Code I used once for similar task was this:

$url  = '"https://www.example.com/test.pdf';
$savePath= 'test.pdf';


$ch = curl_init($url);
if($ch === false)
{
    die('Failed to create curl handle');
}

$fp = fopen($savePath, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

Also you can try with "disabling" headers:

 curl_setopt($soap_do, CURLOPT_HTTPHEADER, 0);

EDIT 2:

Another few SA questions that might help you:

Download remote PDF using php code

why my downloaded file is alwayes damaged or corrupted?