如何将图像下载到PHP中的文件夹 [英] how to download images to a folder in php

查看:111
本文介绍了如何将图像下载到PHP中的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网址下载图片但是没有下载。请查看代码并告诉我哪里出错。

I want to download a image from the url but it is not getting downloaded.Please check out the code and tell me where i am going wrong.

<?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);
?>


推荐答案

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,甚至可以进行基本测试以查看是否确实下载了图像。

If you see any problems, please let me know. This occasionally gives me a 0 byte image file but that could happen for any number of reasons. This could be improved to return false on 0 bytes, maybe even do a basic test to see if indeed an image was downloaded.

这篇关于如何将图像下载到PHP中的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆