Search code examples
arrayscurlphpgetimagesize

PHP newbie CURL and array


UPDATED: I've simplified the code (tried to)

I'm trying to download a series of images as set in an array, but something is clearly not right:

function savePhoto($remoteImage,$fname) {
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_NOBODY, true);
    curl_setopt ($ch, CURLOPT_URL, $remoteImage);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
    $fileContents = curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($retcode==200) {
        $newImg = imagecreatefromstring($fileContents);
        imagejpeg($newImg, ".{$fname}.jpg",100);
    }
    return $retcode;
}

$filesToGet = array('009');
$filesToPrint = array();

foreach ($filesToGet as $file) {
        if(savePhoto('http://pimpin.dk/jpeg/'.$file.'.jpg',$file)==200) {
            $size = getimagesize(".".$file.".jpg");
            echo $size[0] . " * " . $size[1] . "<br />";
        }
}

I get the following errors:

Warning: imagecreatefromstring() [function.imagecreatefromstring]: Empty string or invalid image in C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php on line 15

Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php on line 16

Warning: getimagesize(.009.jpg) [function.getimagesize]: failed to open stream: No such file or directory in C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php on line 26 *


Solution

  • try this instead:

    function get_file1($file, $local_path, $newfilename)
    {
        $err_msg = '';
        echo "<br>Attempting message download for $file<br>";
        $out = fopen($newfilename, 'wb');
        if ($out == FALSE){
          print "File not opened<br>";
          exit;
        }
    
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_FILE, $out);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $file);
    
        curl_exec($ch);
        echo "<br>Error is : ".curl_error ( $ch);
    
        curl_close($ch);
        //fclose($handle);
    
    }//end function 
    

    // taken from: http://www.weberdev.com/get_example-4009.html

    or file_get_contents