2

特定の Web サイトから画像リンクを取得するこのスクリプトがあるため、対応するディレクトリに画像を配置するために使用される Web サイトの画像リンクとソース名を渡す関数を作成しました。

ただし、この関数は適切に機能しない場合があり、ランダムに画像を保存しますが、画像は基本的に空です。そのため、$img_link から元のファイル名で空のファイルを保存するだけで、実際の画像を表示できません。

その場合、それが発生した場合、デフォルトの画像パスを返そうとしました。しかし、それは失敗し、上記で説明したように空の画像を返します。

function saveIMG($img_link, $source){

$name = basename($img_link); // gets basename of the file image.jpg
$name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_" .$name;
if (!empty($img_link)){
    $ch = curl_init($img_link);
    $fp = fopen("images/$source/$name", 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($ch, CURLOPT_HEADER, 0);

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

    $name ="images/$source/$name";
    return $name;
}
else {
    $name = "images/news_default.jpg";
    return $name;
   }
}

画像の取得に失敗した場合のケースを作成する方法について、より良いアイデアはありますか?

ありがとう

4

2 に答える 2

5

file_get_content常に cURL の優れた代替手段です。

ただし、cURL を使用する必要がある場合は、次のようにします。

$ch = curl_init("www.path.com/to/image.jpg");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //Return the transfer so it can be saved to a variable
$result = curl_exec($ch);  //Save the transfer to a variable
if($result === FALSE){//curl_exec will return false on failure even with returntransfer on
    //return? die? redirect? your choice.
}
$fp = fopen("name.jpg", 'w'); //Create the empty image. Extension does matter.
fwrite($fp, $result); //Write said contents to the above created file
fclose($fp);  //Properly close the file

以上です。それをテストし、動作します。

于 2015-04-08T14:10:57.163 に答える
1

ファイル取得コンテンツを使用

$data = file_get_contents($img_link);
//check  it return data or not
if ( $data === false )
{
   echo "failed";
}
于 2015-04-08T14:05:52.403 に答える