简体   繁体   中英

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

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM