【问题标题】:how to download images to a folder in php如何将图像下载到php中的文件夹
【发布时间】:2014-12-31 22:30:39
【问题描述】:

我想从 url 下载图片,但没有下载。请检查代码并告诉我哪里出错了。

<?php
$ch = curl_init ("http://l1.yimg.com/t/frontpage/cannes_anjelina_60.jpg");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen("img.jpg",'w');
fwrite($fp, $rawdata);
fclose($fp);
?>

【问题讨论】:

  • 遇到任何错误?可以设置error_reporting(E_ALL)吗?

标签: php image curl


【解决方案1】:

它工作正常,为应该保存图像的位置设置适当的文件权限。在这种情况下,它与您的脚本所在的文件夹相同,可能希望将其移动到其他位置,例如:

// where "images" folder can be written with files
// set permissions to 0755
$fp = fopen("images/img.jpg",'w');

【讨论】:

    【解决方案2】:
    function download_image ($url, $the_filename) {
    
        $cookie = tempnam ("/tmp", "CURLCOOKIE");
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Debian) Firefox/0.10.1");
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_ENCODING, "");
        curl_setopt($ch, CURLINFO_EFFECTIVE_URL, true);
        curl_setopt($ch, CURLOPT_REFERER, "http://tomakefast.com");
        curl_setopt($ch, CURLOPT_POST, false);
        $rawdata=curl_exec($ch);
        curl_close($ch);
        file_put_contents("../somewhere/". $the_filename, $rawdata);
    
    }
    

    如果您发现任何问题,请告诉我。这偶尔会给我一个 0 字节的图像文件,但这可能由于多种原因而发生。这可以改进为在 0 字节上返回 false,甚至可以进行基本测试以查看是否确实下载了图像。

    【讨论】:

      【解决方案3】:

      如果您觉得这样更好,可以改用这个简单的代码。

      $img_file = file_get_contents("http://l1.yimg.com/t/frontpage/cannes_anjelina_60.jpg");
      file_put_contents("myImage.jpg", $img_file);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 2016-03-10
        • 1970-01-01
        • 2020-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多