【问题标题】:curl_exec succeeds but the output file is emptycurl_exec 成功但输出文件为空
【发布时间】:2011-12-21 00:45:05
【问题描述】:

我在下面编写了 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;
    }
}

【问题讨论】:

  • 如果您尝试对 $downloaded 变量进行 vardump 和/或删除 CURLOPT_FILE 会发生什么情况,您是否看到 CURL 上的任何内容正常通过?
  • 和 (CURLOPT_BINARYTRANSFER, 1) 用于 exe(或在我的情况下为 excel)文件 :-)

标签: php curl download


【解决方案1】:

该网址重定向到另一个。您需要将 CURLOPT_FOLLOWLOCATION 设置为 1 才能正常工作。

【讨论】:

    【解决方案2】:

    尝试添加;

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); //然后在 curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);

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

    【讨论】:

    • 不确定这是否适用于所有人,但这对我来说是 Windows 问题。 Mac/Unix 的同事无法重现它。
    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多