tags:

views:

133

answers:

2

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?

+6  A: 

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.

Paul Dixon
Is that far more efficient than my simple method?
Joshxtothe4
It would consume less memory, since the script only ever holds 32KB of image data.
Paul Dixon
You don’t even have to buffer it.
Gumbo
One way or another, you're buffering it
Paul Dixon
That’s true, but you don’t buffer it redundantly.
Gumbo
+2  A: 

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.

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