2011-11-01 74 views
5

我需要將圖像從url直接保存到我的服務器,我已經嘗試了很多方法,但似乎都無法正常工作。 file_put_contents($file_location, file_get_contents($image_url));讓我沒有找到文件目錄找到錯誤。簡單的fopenfwrite不斷返回損壞的圖像。這一個工作,但它不斷返回HTML文件,而不是JPG文件。從URL保存圖像與cURL

function getimg($url) {   
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';    
    $headers[] = 'Connection: Keep-Alive';   
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';   
    $user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';   
    $process = curl_init($url);   
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);   
    curl_setopt($process, CURLOPT_HEADER, 0);   
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent);   
    curl_setopt($process, CURLOPT_TIMEOUT, 30);   
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);   
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);   
    $return = curl_exec($process);   
    curl_close($process);   
    return $return;  
} 

$imgurl = 'http://some/url/to/image.jpg'; 
$imagename= basename($imgurl); 
if(file_exists('./image/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('image/'.$imagename,$image); 

東西不見了?

謝謝。

+0

你確定這是一個你想下載的圖像文件,而不是一個網頁?你得到的HTML文件包含什麼? – JJJ

回答

3

你的代碼工作正確。它從給定的URL下載圖像。

你的問題將在圖像存儲的路徑。

if(file_exists('./image/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('image/'.$imagename,$image); 

在上面的代碼檢查./image/並給予路徑作爲file_put_contents路徑的路徑。

+0

對不起,我找到了解決方案,URL(圖像名稱)有'空間'字符,所以我必須用'%20'替換它們。感謝您的回覆。 – Hebbian

2

此方法效果:

<?php 

file_put_contents("/var/www/test/test.png", file_get_contents("http://www.google.com/intl/en_com/images/srpr/logo3w.png")); 

?> 

您需要啓用allow_url_fopen,它是最簡單的方法。見http://php.net/manual/en/features.remote-files.php