Home > Back-end >  php curl_exec() Connection refused when retrieving a remote image
php curl_exec() Connection refused when retrieving a remote image

Time:12-09

I want to retrieve a remote hosted image with php. The image exists, I can access to it with my browser. However the result of the curl_exec() is empty and the curl_error() says:

Failed to connect to img107.xooimage.com port 80: Connection refused

Here is my code:

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_URL, 'http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png');
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                $image = curl_exec($ch);

                if( empty($image) ){
                    echo("Impossible to retrieve the file !<br>
                    error: ".curl_error($ch)."<br>");
                }

If I can open the image with my browser, then why the connection is refused when I use curl?

Remark: it works for images from my own domain, but not with external images like the one in the example.

CodePudding user response:

You need to close the curl before reading it

$ch = curl_init('http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
$image = curl_exec($ch);
if (curl_errno($ch)) {  
    print_r(curl_error($ch));  
    die;
}
curl_close($ch);
return $image;

CodePudding user response:

After testing, the following does save the given image into the file image.png along the script, and is readable. Is it what was missing?

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://img107.xooimage.com/files/5/0/b/ss-2014-06-15-at-12.58.47--46324f5.png');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$image = curl_exec($ch);
var_dump($image); // Binary content
$save = fopen('image.png', 'w');
fwrite($save, $image);
fclose($save);
curl_close($ch);
  • Related