|  | Posted by Rik on 07/24/07 19:28 
On Tue, 24 Jul 2007 21:00:54 +0200, Férnas <garbage@wideweb.com.br> wrote:
 > Hello all,
 >
 > How can I save a image that is on internet (eg:
 > http://www.example.com/_img/layout/logo.gif)???
 >
 > I would like to save the image on my server...
 
 If allow_url_fopen[1] is enabled:
 <?php
 
 $url = 'http://example.com/image.jpg';
 $savedir = '/tmp'; //or anything else you want
 $overwrite = true; //or false if image has to be renamed on duplicate
 
 $urlinfo = parse_url($url);
 $filename = basename($urlinfo['path']);
 $target = $savedir.'/'.$filename;
 if(file_exists($target) && !$overwrite){
 //break up file in parts:
 $pathinfo = pathinfo($target);
 //max 50 tries
 $max = 50;
 //loop
 for($i = 1;$i<=$max;$i++){
 $target = $pathinfo['dirname']. '/' . $pathinfo['filename'] . '[' . $i
 .. '].' . $pathinfo['extention'];
 //break on success, do not use file_exists to avoid race
 $fh = @fopen($target,'x');
 if($fh) break;
 }
 //alternatively, if you don't care about the name, you can just:
 //$target = tempnam($savedir);
 if(!$fh) die('Too many retries, no unique filename found.');
 } else {
 $fh = fopen($target,'w');
 }
 $check = fwrite($fh,file_get_contents($url));
 fclose($fh);
 echo (($check) ? 'Successfully saved '.$target : 'Failure');
 ?>
 
 
 
 
 
 [1]http://nl2.php.net/manual/en/ref.filesystem.php
 --
 Rik Wasmus
  Navigation: [Reply to this message] |