Downloading Multiple Images Using PHP CURL


This question already has an answer here:

  • Saving image from PHP URL 9 answers

I want to download images from a web page, for example,, 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.

    $html = file_get_contents('');
    $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);
        fwrite($fp, $image);

foreach($matches as $img)

should be changed to

foreach($matches[1] as $img)

BTW: you should replace the file_get_contents by cURL, it's about 3x as fast;)