file download with curl and php

2.1k Views Asked by At

I wrote a php function that downloads some (.exe) files using curl extension. The file gets successfully downloaded, but when I try to open it I get not compatible error. I opened it using notepad++ and there I see a '200' added to the beginning of the file. I can't really understand from where this '200' comes ? here is my function:

$source = isset($_GET['link']) ? $_GET['link'] : ''; #get the download link
$filename = isset($_GET['name']) ? $_GET['name'] : 'download.exe'; # define name
if($source != '')
{
            $handle = curl_init($source);
            curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

            /* Get the HTML or whatever is linked in $url. */
            $response = curl_exec($handle);

            /* Check for 403 (forbidden). */
            $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
            if($httpCode == 403) {
                echo "<h2> <font color='red'> Sorry you are not allowed to download that file.</font><h2>";
            } else {
                header("Content-Disposition: attachment; filename=\"{$filename}\"");
                #header("Content-Disposition: attachment; filename=\"uploaded.pdf\"");
                // Get a FILE url to my test document

                $url= str_replace(" ","%20", $source);
                $ch= curl_init($url);
                #curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
                curl_exec($ch);
                curl_close ($ch); 
             }
            curl_close($handle);
}
else {
echo "error";
}
1

There are 1 best solutions below

2
On BEST ANSWER

Set CURLOPT_HEADER to false like:

curl_setopt($ch, CURLOPT_HEADER, false);

It will disable the HTTP response, so you do not will receive the '200' in your file.

Similar question here in SO