2

I have a URL - http://www.xxx.xxx.xxx/

This URL, I'm able to open through the browser. I'm even able to call this URL via cURL from my machine, but when I'm calling it from the code on the same server and domain, it gives me an error - error: couldn't connect to host

Following is my code -

function get_xml_via_curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    echo $url;
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    /*curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);*/
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $returned = curl_exec($ch);
    if(curl_errno($ch)) {
        echo 'error: ' . curl_error($ch);
    }
    curl_close($ch);
    // $xml === False on failure
    $xml = simplexml_load_string($returned);
    return $xml;
}

Like I said, on localhost this works. I can directly open the URL via the browser. But when I deploy the code on the same server and try calling via cURL, it gives me an error - error: couldn't connect to host

Updated Code -

I modified the code on my server to -

function get_xml_via_curl($url) {
    $url = " http://www.xxx.xxx.xxx.xxx/";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $returned = curl_exec($ch);
    if(curl_errno($ch)) {
        echo 'error: ' . curl_error($ch);
    }
    curl_close($ch);
    $xml = simplexml_load_string($returned);
    return $xml;
}

And the error from curl changes to following -

error: Protocol http not supported or disabled in libcurl

Abijeet Patro
  • 2,842
  • 4
  • 37
  • 64

3 Answers3

2

Your updated code is not working because of the white space before http in $url = " http...

The original code is probably not working because of some firewall or nameserver issue. Try to visit the URL you want to load directly in a browser ON THE SAME SERVER. That will probably fail too.

You need to fix the server to accept requests from the localhost.

What can also help you on your way is to check the web server and firewall log files. See why the requests are being declined. And even temporarily just disable the firewall to rule it out.

nl-x
  • 11,762
  • 7
  • 33
  • 61
1

I have faced the same, PHP curl throwing 'Connection timeout error' because of same domain and tried all other options, but nothing worked out.

Finally I got the answer and fixed it. Just run below command (ubuntu)

# sudo ifconfig lo up

For Cent OS:

# sudo ip link set lo up
# sudo ip addr show

"lo" is the loopback interface. This is a special network interface that the system uses to communicate with itself.

Sudharshan
  • 11
  • 1
0

try:

$url="//your url";
echo get_xml_via_curl($url);
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44