2011-11-01 14 views
5

URLから画像を直接サーバーに保存する必要がありますが、多くの方法を試しましたが、すべて正常に動作しないようです。 file_put_contents($file_location, file_get_contents($image_url));は、ファイルディレクトリが見つかりませんでした。 fopenfwriteは壊れたイメージを返し続けます。これはうまくいったが、jpgファイルの代わりにhtmlファイルを返す。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

関連する問題