PHP - getting an image and saving it locally

Soldato
Joined
4 Jul 2004
Posts
2,647
Location
aberdeen
Hello
First this isn't just to go about nicking peoples work. It is to be used (privatly) with product images, that are (probably?) taken by the manufacturers and given out with press releases

Anyway, I want the user [me] to enter a url for an image (eg http://www.example.com/pic.jpg), in a field. Then on the submit page, it gets that image, gives it a unique name, saves it in a local folder (http://www.....com/imgs/), then stores the file name to a database

I can do all the DB stuff, its just getting the image and saving it that i am not sure about

Hope this makes sense

Any ideas/links?

Thanks
 
if your running php5 it is a 1 liner:

Code:
<?php

file_put_contents('test.gif', file_get_contents('http://uk2.php.net/images/php.gif'));

?>

otherwise for php4 something like this:

Code:
<?php

$handle = fopen('test.gif', 'a+b');
fwrite($handle, file_get_contents('http://uk2.php.net/images/php.gif'));
fclose($handle);

?>
 
Or for portability, look into using an external library such as cURL or (my preference) Snoopy. With Snoopy, you'd do:

Code:
require_once 'snoopy.php';

$snoopy = new snoopy();

$snoopy->fetch('http://domain.com/image.png');

$fh = fopen('/path/to/local/image.png', 'w');
fwrite($fh, $snoopy->results);
fclose($fh);
 
jonno.co.uk said:
how is using an external library more portable than using PHP's built in functions :p

the only way my above examples won't work is if your host has the fopen wrappers disabled (unlikely).

Because the former will always work, and the latter might not? My host has allow_url_fopen turned off, as do a lot of others.
 
Back
Top Bottom