如何使用php curl将远程图片保存到文件?

3

我正在尝试使用PHP Curl将远程图片保存到文件中,但是文件从未被保存!有没有人能帮助我解决这个问题?图片文件从未被创建,但是echo $returned_content返回了数据!

 <?
    $returned_content = get_data('http://somesite.com/43534545345dfsdfdsfdsfds.jpg');

    echo $returned_content;

    $fp = fopen('43534545345dfsdfdsfdsfds.jpg', 'w');
    fwrite($fp, $returned_content);
    fclose($fp);


    /* gets the data from a URL */
    function get_data($url) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }




    ?>

当您回显 $returned_content 时,是否看到数据?同时将 'w' 更改为 'wb'。 - craftand
谢谢回复。是的,我看到了数据。如果不创建安全问题,那么对于包含 PHP 脚本的文件夹,应该放置什么 chmod 权限? - user1788736
755通常应该没问题。 - craftand
我尝试了755,但是出现错误,无法打开文件43534545345dfsdfdsfdsfds.jpg! - user1788736
2个回答

6
<?php         
$ch = curl_init('http://www.example/2012/09/flower.jpg');
$fp = fopen('/localProject/imagesFolder/newname.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);     
?>

0

试试这个

 <?php
function getImagen($url, $rename, $ch)
{
$ch = curl_init($url);
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("$rename.jpg",'w');
fwrite($fp, $rawdata); 
fclose($fp);             
}

$ch = curl_init();
$image ="http://sampleurl.com/imagen.jpg";

getImagen ($image, "imagen", $ch);
?>

完美运行 100% :)


我应该为包含脚本的文件夹设置什么chmod?如何使用与原始文件名相同的文件名?例如,如何使用任何动态图像URL的文件名并使用该名称保存该图像?如何检查错误以确定文件是否已保存? - user1788736
使用file_exist进行错误检查,在脚本的var $rename中,您可以保存任何名称。(对我的英语表示抱歉)也许包含脚本的文件夹需要权限。 - Amulo
请注意,这需要在写入文件之前将整个文件保存在内存中。这会浪费内存,并且在处理较大的文件时会失败。请参阅CURLOPT_FILE,以允许curl在主动下载远程资源时将其写入文件。 - Cheekysoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接