Tom Dong
Tom Dong

Reputation: 79

Sometimes my PHP function doesn't work well

I wrote a php function to copy an internet image to local folder, sometimes it works well, but sometimes it just generate an invalid file with size of 1257B.

function copyImageToLocal($url, $id)
{
    $ext=strrchr($url, "."); 
    $filename = 'images/' . $id . $ext;

    ob_start(); 
    readfile($url); 
    $img = ob_get_contents(); 
    ob_end_clean();

    $fp=@fopen($filename, "a"); 
    fwrite($fp, $img); 
    fclose($fp); 
}

Note: The $url passed in is valid, sometimes this function fails at first time, but may successful for the second or third time. It's really strange... Does this require some special PHP settings?

Please help me!


I have found the real reason: the test image url is not allowed for program accessing, though it can be opened in browser. I tried some other image url, the function works well.

So, it seems I need find a way to process this kind of cases. Thanks guys!

Upvotes: 0

Views: 256

Answers (1)

immulatin
immulatin

Reputation: 2118

Why don't you just open the file and write it to the disk like so:

file_put_contents($filename, fopen($url, 'r'));

This will even do buffering for you so you shouldn't run into memory problems (since you are storing the whole image in memory before writing it to a file)

Upvotes: 1

Related Questions