Sunday, March 27, 2011

Best way to store an image from a url in php?

Hello,

I would like to know the best way to save an image from a URL in php.

At the moment I am using

file_put_contents($pk, file_get_contents($PIC_URL));

which is not ideal. I am unable to use curl. Is there a method specifically for this?

From stackoverflow
  • Using file_get_contents is fine, unless the file is very large. In that case, you don't really need to be holding the entire thing in memory.

    For a large retrieval, you could fopen the remote file, fread it, say, 32KB at a time, and fwrite it locally in a loop until all the file has been read.

    For example:

    $fout = fopen('/tmp/verylarge.jpeg', 'w');
    $fin = fopen("http://www.example.com/verylarge.jpeg", "rb");
    while (!feof($fin)) {
        $buffer= fread($fin, 32*1024);
        fwrite($fout,$buffer);
    }
    fclose($fin);
    fclose($fout);
    

    (Devoid of error checking for simplicity!)

    Alternatively, you could forego using the url wrappers and use a class like PEAR's HTTP_Request, or roll your own HTTP client code using fsockopen etc. This would enable you to do efficient things like send If-Modified-Since headers if you are maintaining a cache of remote files.

    Joshxtothe4 : Is that far more efficient than my simple method?
    Paul Dixon : It would consume less memory, since the script only ever holds 32KB of image data.
    Gumbo : You don’t even have to buffer it.
    Paul Dixon : One way or another, you're buffering it
    Gumbo : That’s true, but you don’t buffer it redundantly.
  • I'd recommend using Paul Dixon's strategy, but replacing fopen with fsockopen(). The reason is that some server configurations disallow URL access for fopen() and file_get_contents(). The setting may be found in php.ini and is called allow_url_fopen.

    Paul Dixon : but as he's using file_get_contents with url wrappers, this wouldn't apply
    IonuČ› G. Stan : He may be unaware of the problem. So a portable solution would drop fopen() and file_get_contents().

0 comments:

Post a Comment