使用cURL保存远程图像?

时间:2010-05-18 09:11:06

标签: php curl gd

早上好,

围绕这个问题提出了几个问题,但根据我的理解,没有一个真正回答我的问题。基本上我有一个GD脚本来处理我们服务器上的图像大小调整和缓存,但我需要对存储在远程服务器上的图像做同样的事情。

所以,我想在本地保存图像,然后调整大小并正常显示它。

我到目前为止......

        $file_name_array = explode('/', $filename);
        $file_name_array_r = array_reverse($file_name_array);  

        $save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0];

        $ch = curl_init($filename);
        $fp = fopen($save_to, "wb");

        // set URL and other appropriate options
        $options = array(CURLOPT_FILE => $fp,
                         CURLOPT_HEADER => 0,
                         CURLOPT_FOLLOWLOCATION => 1,
                         CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough)

        curl_setopt_array($ch, $options);

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

这会创建图像文件,但不会复制它吗?我错过了这一点吗?

干杯队员。

3 个答案:

答案 0 :(得分:3)

更简单,您可以使用 file_put_contents 代替 fwrite

$file_name_array = explode('/', $filename);
$file_name_array_r = array_reverse($file_name_array);  
$save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0];
file_put_contents($save_to, file_get_contents($filename));

或仅仅2行:)

$file_name_array_r = array_reverse( explode('/', $filename) );  
file_put_contents('system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0], file_get_contents($filename));

答案 1 :(得分:2)

好吧,我把它分类了!在检查了我的图像而不是我的代码更接近之后,结果发现一些图像在他们身边而不是我的错误。一旦我选择了有效的图像,我的代码也能正常工作!

一如既往的欢呼!)

答案 2 :(得分:0)

我个人不喜欢使用写入文件的curl函数。试试这个:

    $file_name_array = explode('/', $filename);
    $file_name_array_r = array_reverse($file_name_array);  

    $save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0];

    $ch = curl_init($filename);
    $fp = fopen($save_to, "wb");

    // set URL and other appropriate options
    $options = array(CURLOPT_HEADER => 0,
                     CURLOPT_FOLLOWLOCATION => 1,
                     CURLOPT_TIMEOUT => 60,
                     CURLOPT_RETURNTRANSFER, true //Return transfer result
                     );

    curl_setopt_array($ch, $options);
    //Get the result of the request and write it into the file
    $res=curl_exec($ch);
    curl_close($ch);
    fwrite($fp,$res);
    fclose($fp);

但是你可以使用更简单的东西而不用卷曲:

$file_name_array = explode('/', $filename);
$file_name_array_r = array_reverse($file_name_array);  
$save_to = 'system/cache/remote/'.$file_name_array_r[1].'-'.$file_name_array_r[0];
$content=file_get_contents($filename); 
$fp = fopen($save_to, "wb");
fwrite($fp,$content);
fclose($fp);