Vitaly
Vitaly

Reputation: 4488

curl_exec succeeds but the output file is empty

I wrote the PHP function below to download files and it works as expected. However, when I try to download this file:

$url = 'http://javadl.sun.com/webapps/download/GetFile/1.7.0_02-b13/windows-i586/jre-7u2-windows-i586-iftw.exe';
download($url);

... no content is written to the file. And I can't figure out why. The file is created, the call to curl_exec returns true, but the output file remains empty. The file can be downloaded in the browser just fine and the function successfully downloads other files. It's just this file (host?) that I'm having problem with.

Any help is appreciated.

function download($url)
{
    $outdir = 'C:/web/www/download/';
    // open file for writing in binary mode
    if (!file_exists($outdir)) {
        if (!mkdir($outdir)) {
            echo "Could not create download directory: $outdir.\n";
            return false;
        }
    }
    $outfile = $outdir . basename($url);
    $fp = fopen($outfile, 'wb');
    if ($fp == false) {
        echo "Could not open file: $outfile.\n";
        return false;
    }
    // create a new cURL resource
    $ch = curl_init();
    // The URL to fetch
    curl_setopt($ch, CURLOPT_URL, $url);
    // The file that the transfer should be written to
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $header = array(
        'Connection: keep-alive',
        'User-Agent: Mozilla/5.0',
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    // downloading...
    $downloaded = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    fclose($fp);

    if (!$downloaded) {
        echo "Download failed: $error\n";
        return false;
    } else {
        echo "File successfully downloaded\n";
        return $outfile;
    }
}

Upvotes: 2

Views: 5601

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Try Adding;

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
//then after curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);

Check some sample: http://www.php.net/manual/en/function.curl-exec.php#84774

Upvotes: 4

a sad dude
a sad dude

Reputation: 2825

That url redirects to another. You need to set CURLOPT_FOLLOWLOCATION to 1 for that to work.

Upvotes: 5

Related Questions