2011-05-15 88 views
1

我想下載一個圖像從網址,但它沒有得到下載。請檢查代碼,並告訴我哪裏出錯了。如何下載圖像到一個文件夾在php

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

獲取任何錯誤?你可以設置'error_reporting(E_ALL)'? – Brad 2011-05-15 03:21:32

回答

1

它工作正常,設置適當的文件權限,以保存圖像的位置。在這種情況下,它也正是你的腳本,可能要到別的地方去移動它就像同一個文件夾:

// where "images" folder can be written with files 
// set permissions to 0755 
$fp = fopen("images/img.jpg",'w'); 
0

你可以使用這個簡單的代碼,而不是如果你覺得這是更好的。

$img_file = file_get_contents("http://l1.yimg.com/t/frontpage/cannes_anjelina_60.jpg"); 
file_put_contents("myImage.jpg", $img_file); 
1
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,甚至可以做一個基本的測試,看看是否確實下載了一個圖像。

相關問題