Jackson
Jackson

Reputation: 820

PHP: download images from array of urls?

I'm trying to download all the images from an array and store them on my server using PHP.

This is my PHP code:

$IMAGES = 'http://url.com/image.jpg, http://url.com/image2.jpg, http://url.com/image-test.jpg, http://url.com/image6.jpg, http://url.com/image.jpg';

$images = array(''.$IMAGES.''); 

foreach($images as $name=>$image) {

    $name = explode(",", $image);

    $name0 = implode(" ",$name);

    copy(''.$name0.'', '/test/'.$name0.'.jpg');     


}

When I run my code, I don't get any images stored on my server and I get a warning message on my php page.

Could someone please advise on this issue?

The warning message I get is this:

Warning: copy(/test/http:/url.com/image.jpg http:/url.com/image2.jpg in line 88

and this is on line 88:

copy(''.$name0.'', '/test/'.$name0.'.jpg'); 

Upvotes: 1

Views: 1794

Answers (2)

Think Different
Think Different

Reputation: 2815

Try the following:

$IMAGES = 'http://url.com/image.jpg, http://url.com/image2.jpg, http://url.com/image-test.jpg, http://url.com/image6.jpg, http://url.com/image.jpg';

$images = explode(', ',$IMAGES); 

foreach($images as $image) {

   $name = basename($image);
   $newfile = $_SERVER['DOCUMENT_ROOT'] .'/test/'.$name;

   if(copy($image, $newfile)){
      echo 'Successfully downloaded '. $image;
   }else{
      echo 'Download failed for '. $image;
   }

}

Upvotes: 2

Kasper Sanguesa-Franz
Kasper Sanguesa-Franz

Reputation: 617

Your array is containing 1 list for it to work you have to do something like this

$images= array(
  'http://url.com/image.jpg', 
  'http://url.com/image2.jpg',
  'http://url.com/image-test.jpg',
  'http://url.com/image6.jpg', 
  'http://url.com/image.jpg'
);

You can't make a string to a array the way you want - you can however use explode to "explode" the string to a array by doing something like this

$images = explode(',',$IMAGES);

you however get a problem with urls with a , in it

Upvotes: 0

Related Questions