I want to download images from a web page, for example, www.yahoo.com, and store it in a folder using PHP.
I am getting the page source using file_get_contents() and extracting the img src tag. I am passing this src to cURL code. The code does not give any error, but the images are not getting downloaded. Please check out the code. I am not getting where I am going wrong.
<?php
$html = file_get_contents('www.yahoo.com');
$ptn = '/< *img[^>]*src *= *["\']?([^"\']*)/i';
preg_match_all($ptn, $html, $matches, PREG_PATTERN_ORDER);
$seq = 1;
foreach($matches as $img)
{
$fp = fopen("root/Images/image_$seq.jpg", 'wb');
$ch = curl_init ($img);
curl_setopt($ch,CURLOPT_FILE, $fp);
curl_setopt($ch,CURLOPT_URL, $img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$image = curl_exec($ch);
curl_close($ch);
fwrite($fp, $image);
fclose($fp);
$seq++;
}
echo "IMAGES DOWNLOADED";
?>