curl_exec成功,但是输出文件为空

Vit*_*aly 2 php curl download

我在下面编写了PHP函数来下载文件,它可以按预期工作。但是,当我尝试下载此文件时:

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

...没有内容写入文件。我不知道为什么。创建文件后,对curl_exec的调用返回true,但是输出文件保持为空。可以在浏览器中很好地下载文件,并且该功能可以成功下载其他文件。我遇到的只是这个文件(主机?)。

任何帮助表示赞赏。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

a s*_*ude 5

该URL重定向到另一个。您需要将CURLOPT_FOLLOWLOCATION设置为1才能起作用。