curl_exec成功但输出文件为空

时间:2011-12-21 00:45:06

标签: 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);

...没有内容写入文件。我无法弄清楚原因。创建文件后,对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;
    }
}

2 个答案:

答案 0 :(得分:4)

该网址重定向到另一个网址。您需要将CURLOPT_FOLLOWLOCATION设置为1才能生效。

答案 1 :(得分:3)

尝试添加;

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

检查一些示例:http://www.php.net/manual/en/function.curl-exec.php#84774

相关问题