【问题标题】:PHP cURL download does not work when called from browser从浏览器调用 PHP cURL 下载不起作用
【发布时间】:2013-01-12 11:43:35
【问题描述】:

我想要一个可以从浏览器访问的 php 脚本,该脚本会将文件下载到我的远程服务器(而不是我的计算机)。 这是我从浏览器调用的完整代码 localhost/download.php 但它不起作用(在网络管理器中我看到正在下载某些东西但在项目文件夹中我找不到它):

<?  
    function download($url, $referer, $name)
    {
        $path = $name.'.mp3';
        $fp = fopen($path, 'w');
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:13.5) Gecko/20100101 Firefox/13.4.9\r\n',
                    "Referer: $referer" 
        ));
        $data = curl_exec($ch);
        curl_close($ch);
        fwrite($fp, $data);
        fclose($fp);
    }

    echo 'Please wait it is downloading...<br/>';
    /*$url = $_GET['url'];
    $referer = $_GET['referer'];
    $name = $_GET['name'];*/
    $url = "http://stream.get-tune.net/file/91259796/101538464/3652118538/ee58ddeb905ffa12/Palwan_Halmyradow_-_Sensiz_(get-tune.net).mp3";
    $referer = "http://get-tune.net/?a=music&q=palwan+halmyradow";
    $name = "Palwan Halmyradow - Sensiz";
    download($url, $referer, $name);
?>

但是当我从命令行调用以下命令时它可以工作:

php /var/www/idym/download.php

有什么问题?

【问题讨论】:

  • 你在哪里写文件?
  • @vaneto 我想将文件下载到我的服务器。而且出于记忆的原因,我是直接写的。
  • 这里应该可以工作:stackoverflow.com/questions/3926944/… ;)
  • @inkytales 不这么认为

标签: php web-applications


【解决方案1】:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

差异可能是由于 cli php 和 apache php 的配置不同造成的。

http://php.net/manual/en/function.curl-setopt.php

完整代码:

function download($url, $referer, $name)
{
    $path = $name.'.mp3';
    $fp = fopen($path, 'w');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:13.5) Gecko/20100101 Firefox/13.4.9\r\n',
                "Referer: $referer" 
    ));
    $data = curl_exec($ch);
    curl_close($ch);
    fwrite($fp, $data);
    fclose($fp);
}

【讨论】:

  • @torayeff 如果您设置此选项,响应的内容将存储在代码中的 $data 中。你需要运行 file_put_contents('path/to/file', $data);左右保存
  • :) 不懒惰。但它真的不起作用。我用我使用的完整代码编辑了我的问题。
  • 如果我们使用 curl_setopt($ch, CURLOPT_FILE, $fp);我们不需要 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);所以;)
  • 好吧,我的错。我错过了,请添加 var_dump(curl_getinfo($ch));在 curl_close 之前。很可能 apache 用户没有写文件的权限,所以还要检查 fopen 是否不返回 0。
  • 完全正确。我只是想回答我自己的问题:)。文件权限问题。浏览器无法在 /var/www/ 中写入文件。
猜你喜欢
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 2015-10-14
  • 2010-12-28
相关资源
最近更新 更多