6

Possible Duplicate:
save image from php url using php

How can i use php to save/grab an image from another domain(not on my domain/server) and save it in a directory of my site.

The URL of the image for example , will be :

http://anothersite/images/goods.jpg

How can i use PHP to grab "good.jpg" ,and save it in my directory which is www.mysite.com/directory/

I hope someone could guide me. Thanks!

0

2 Answers 2

23

You should be able to use file_get_contents for this one. In order to use an URL with file_get_contents make sure allow_url_fopen is enabled in you php.ini file.

define('DIRECTORY', '/home/user/uploads');

$content = file_get_contents('http://anothersite/images/goods.jpg');
file_put_contents(DIRECTORY . '/image.jpg', $content);

Make sure that you have write permission to the directory where you want to store the image; to make the folder writable you could do this:

chmod +w /home/users/uploads

References

  1. file_get_contents
  2. allow_url_fopen
  3. chmod command
Sign up to request clarification or add additional context in comments.

1 Comment

thanks Krister , but how can i put it in specific directory?
4

This link may be answer your question:

http://stackoverflow.com/questions/909374/copy-image-from-remote-server-over-http

to me the following code should serve ur need:

$url = "http://other-site/image.png";
$dir = "/my/local/dir/";
$lfile = fopen($dir . basename($url), "w");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FILE, $lfile);

fclose($lfile);
curl_close($ch);

1 Comment

You can specify an relative or absolute path to the output file as long as you have write permission to that specific directory.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.