【问题标题】:Save images with CURL, sometimes it saves blank images使用 CURL 保存图像,有时它会保存空白图像
【发布时间】:2015-06-13 12:59:33
【问题描述】:

我有这个脚本,用于从特定网站获取图片链接,因此我创建了一个函数,用于传递网站的图片链接和源名称,用于将图片放置在相应的目录中。

但有时这个功能不能正常工作,它会随机保存图像但是图像基本上是空的,因此它只会保存一个具有$img_link原始文件名的空文件,但无法显示实际图像.

在这种情况下,如果发生这种情况,我会尝试返回默认图像路径。但它没有这样做并返回一个空图像,如上所述。

function saveIMG($img_link, $source){

$name = basename($img_link); // gets basename of the file image.jpg
$name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_" .$name;
if (!empty($img_link)){
    $ch = curl_init($img_link);
    $fp = fopen("images/$source/$name", 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($ch, CURLOPT_HEADER, 0);

    $result = curl_exec($ch);
    curl_close($ch);
    fclose($fp);

    $name ="images/$source/$name";
    return $name;
}
else {
    $name = "images/news_default.jpg";
    return $name;
   }
}

你有什么更好的主意,当它无法检索到图像时如何做一个案例?

谢谢

【问题讨论】:

    标签: php image curl save-image


    【解决方案1】:

    file_get_content 始终是 cURL 的良好替代品。

    但是,如果您想/必须使用 cURL:

    $ch = curl_init("www.path.com/to/image.jpg");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //Return the transfer so it can be saved to a variable
    $result = curl_exec($ch);  //Save the transfer to a variable
    if($result === FALSE){//curl_exec will return false on failure even with returntransfer on
        //return? die? redirect? your choice.
    }
    $fp = fopen("name.jpg", 'w'); //Create the empty image. Extension does matter.
    fwrite($fp, $result); //Write said contents to the above created file
    fclose($fp);  //Properly close the file
    

    就是这样。经过测试,它可以工作。

    【讨论】:

    • 这很好,但我会将fopen() after 收集到$result,这样您就可以测试结果并查看它是否有效你费心打开要写的文件。
    • @Andrew ,我以前使用过 file_get_content ,但我认为使用 cURL 会显示出更好的结果。无论如何,我使用您的建议修改了我的功能,到目前为止它运行良好。谢谢人:)
    【解决方案2】:

    使用文件获取内容

    $data = file_get_contents($img_link);
    //check  it return data or not
    if ( $data === false )
    {
       echo "failed";
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-15
      • 2020-07-25
      • 1970-01-01
      • 2020-04-16
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 2017-03-01
      相关资源
      最近更新 更多