Home > front end >  Downloading Images from list of URL to server using PHP
Downloading Images from list of URL to server using PHP

Time:02-13

I made a simple script that can download image from the URL. It perfectly works.

$img_link = 'https://samplesite.com/image.jpg';
$imge_title = basename($img_link);


$ch = curl_init($img_link);
$fp = fopen("folder/".$imge_title, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

The next thing to is to Download a list of URLS from a txt file and process them per line.

https://samplesite.com/image_1.jpg
https://samplesite.com/image_2.jpg
https://samplesite.com/image_3.jpg
https://samplesite.com/image_4.jpg
https://samplesite.com/image_5.jpg

Here's what I came up with:

$lines = file( 'List.txt' ); //the list of image URLs

foreach ( $lines as $line ) {
$img_link = $line;
$imge_title = basename($img_link); //I want to retain the original name of the file


$ch = curl_init($img_link);
$fp = fopen($imge_title, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}

It doesn't work and I keep getting Warnings:

Warning: fopen(image_1.jpg): failed to open stream: No such file or directory
Warning: curl_setopt(): supplied argument is not a valid File-Handle resource
Warning: fclose() expects parameter 1 to be resource

CodePudding user response:

As the file doc says, the file's newlines are preserved in the resulting array:

Each element of the array corresponds to a line in the file, with the newline still attached.

Pass the FILE_IGNORE_NEW_LINES flag to the file(...) call.

Otherwise, most or all of your $line values will end with a '\n' or '\r' character.

You should probably also pass FILE_SKIP_EMPTY_LINES.

$lines = file( 'List.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ); //the list of image URLs
  • Related