2013-11-04 84 views
3

我想將遠程圖像保存到使用php curl的文件,但文件永遠不會保存!任何人可以幫助我如何解決這個問題?圖像文件永遠不會被創建,但echo $ returned_content有數據!如何使用php curl將遠程圖像保存到文件?

<? 
    $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; 
    } 




    ?> 
+0

當U回聲$ returned_content你看到的數據?還要將'w'改爲'wb' – craftand

+0

謝謝reply.yes我看到數據。我應該把哪個chmod文件夾放在沒有產生安全問題的php腳本中? – user1788736

+0

755應該是正常的 – craftand

回答

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%:)

+0

什麼chmod應該放在包含腳本的文件夾中?以及如何使用與原始文件名相同的文件名?例如如何使用任何動態圖像url的文件名並使用該名稱來保存該圖像?如何檢查文件是否保存錯誤? – user1788736

+0

使用file_exist進行錯誤檢查,並在腳本的var $ rename中保存任何名稱。 (對不起,我的英文)和...也許你的文件夾包含腳本需要許可。 – Amulo

+0

請注意,這需要在寫入之前將整個文件保存在內存中。浪費內存並在較大的文件上失敗。請參閱CURLOPT_FILE以允許curl寫入文件,因爲它正在主動下載遠程資源 – Cheekysoft

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