82

I send an item code to a web service in xml format using cUrl(php). I get the correct response in localhost, but when do it server it shows

cURL Error (7): couldn't connect to host

And here's my code:

function xml_post($post_xml, $url)
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $ch = curl_init();    // initialize curl handle
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);          
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 50); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); 
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
//  curl_setopt($ch, CURLOPT_PORT, $port);          

    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    if ($curl_errno > 0) {
            echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
            echo "Data received\n";
    }
    curl_close($ch);

    echo $data;
}

I send the item code to the tally and fetch the details from it. I tried using both the versions php 4+ and php5+, nothing works out Any solution.

Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
Raj
  • 943
  • 2
  • 10
  • 12

13 Answers13

57

CURL error code 7 (CURLE_COULDNT_CONNECT)

is very explicit ... it means Failed to connect() to host or proxy.

The following code would work on any system:

$ch = curl_init("http://google.com");    // initialize curl handle
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
print($data);

If you can not see google page then .. your URL is wrong or you have some firewall or restriction issue.

Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
Baba
  • 94,024
  • 28
  • 166
  • 217
  • I'm able to see the google page. But then the same url i use it in localhost and there it works fine. – Raj Mar 29 '12 at 10:13
  • Its your URL ... can you give a sample URL let me test for you – Baba Mar 29 '12 at 10:58
  • How to over come firewall issue. – Raj Mar 29 '12 at 11:26
  • 1
    I don't think that is a public available ip address http://network-tools.com/default.asp?prog=express&host=122.165.82.61 Pinging 122.165.82.61 with 32 bytes of data: Request timed out. Request timed out. Request timed out. Request timed out. – Baba Mar 30 '12 at 09:03
  • Hey guys, I am also trying to send a file using the PHP curl and getting error code 7 which is unable to connect to host, I tried Baba's approach to check if google.com gets loaded and it does. the ip address I'm trying to ftp is publicly available as when i ping to the ip it gives (64 bytes from 31.170.160.98: icmp_req=1 ttl=42 time=249 ms) the IP is of course - 31.170.160.98, Also when I try to ftp using a browser it allows me to enter. But its the curl script that creates the error. Can anyone help me to resolve this or point me in what needs to be checked eg firewall, ports etc. – itsandy May 08 '13 at 01:20
  • See http://stackoverflow.com/questions/1178425/download-a-file-from-ftp-using-curl-and-php on how to connect to FTP – Baba May 08 '13 at 01:37
  • thanks but i found that I was using the wrong hostname to connect. All working now. thanks – itsandy May 09 '13 at 03:50
  • 4
    @Baba You said: `If you can not see google page then .. your URL is wrong or you have some firewall or restriction issue.` what kind of restrictions may exist? – hpaknia Jul 26 '13 at 08:04
  • 2
    @hpaknia thanks, sometimes we fail to see the obvious... Complementing your response, in Linux systems, remember to check ACL and SELinux permissions regarding your webservice's access to the file being executed. – Jorge_Freitas Oct 29 '19 at 22:51
  • I've changed from 81 to default 80 port and it solved my problem. I wonder why this works, considering that from another server I had success requests for port 81. Thanks! – Oleg Reym Jul 10 '20 at 08:11
33

“CURL ERROR 7 Failed to connect to Permission denied” error is caused, when for any reason curl request is blocked by some firewall or similar thing.

you will face this issue when ever the curl request is not with standard ports.

for example if you do curl to some URL which is on port 1234, you will face this issue where as URL with port 80 will give you results easily.

Most commonly this error has been seen on CentOS and any other OS with ‘SElinux’.

you need to either disable or change ’SElinux’ to permissive

have a look on this one

http://www.akashif.co.uk/php/curl-error-7-failed-to-connect-to-permission-denied

Hope this helps

Ali
  • 552
  • 6
  • 17
  • 3
    But how about mac system – MeganZhou May 12 '14 at 11:07
  • 8
    Disabling SELinux is overkill and will negatively affect security in other areas. You can explicitly allow for ports other than the known ones by changing that specific option from the terminal: setsebool -P httpd_can_network_connect on – Matthew Erwin Oct 27 '14 at 23:06
  • Is there a list of standard ports, for which curl does not throw this error? – Michael Radionov Jul 07 '16 at 15:54
  • In my case, the server has a list of allowed connections and blocks all connections that are not in that list – jking Jan 14 '20 at 11:59
  • `setsebool -P httpd_can_network_connect on` did not work for me (on Centos 8, trying to get fail2ban curl-ing to a webhook whenever ban/unbans triggers). Do you have to call this on any particular current directory, or will this apply the selinux bool from any directory? – chamberlainpi Dec 04 '20 at 15:11
  • I recommend to add the ``nano /etc/selinux/config`` lines to this answer (mentioned on the linked site) – dingalapadum Jan 29 '21 at 23:48
21

If you have tried all the ways and failed, try this one command:

setsebool -P httpd_can_network_connect on
Iman Marashi
  • 5,593
  • 38
  • 51
  • 2
    This just saved me after hours of chasing the wrong bugs on a very old PHP script during a server migration. The only error in my logs was `[7]` which I didn't realize was from curl. I stumbled on this answer and it's back up and running! – sofly Aug 20 '21 at 00:21
  • I really can't comprehend my self. well my selinux capability really shallow :/ – Benyamin Limanto Apr 05 '22 at 06:00
5

In PHP, If your network under proxy. You should set the proxy URL and port

curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number

This is solves my problem

Krishna Mohan
  • 1,503
  • 3
  • 22
  • 28
prince jose
  • 193
  • 1
  • 7
4

In my case I had something like cURL Error (7): ... Operation Timed Out. I'm using the network connection of the company I'm working for. I needed to create some environment variables. The next worked for me:

In Linux terminal:

$ export https_proxy=yourProxy:80
$ export http_proxy=yourProxy:80  

In windows I created (the same) environment variables in the windows way.

I hope it helps!

Regards!

Jason Roman
  • 8,146
  • 10
  • 35
  • 40
2

Are you able to hit that URL by browser or by PHP script? The error shown is that you could not connect. So first confirm that the URL is accessible.

jokerdino
  • 2,047
  • 1
  • 25
  • 31
Mohan Shanmugam
  • 644
  • 1
  • 6
  • 18
1

Check if port 80 and 443 are blocked. or enter - IP graph.facebook.com and enter it in etc/hosts file

WhiteHorse
  • 718
  • 2
  • 8
  • 15
1

you can also get this if you are trying to hit the same URL with multiple HTTP request at the same time.Many curl requests wont be able to connect and so return with error

dv3
  • 151
  • 2
  • 12
1

This issue can also be caused by making curl calls to https when it is not configured on the remote device. Calling over http can resolve this problem in these situations, at least until you configure ssl on the remote.

Scott T Rogers
  • 515
  • 4
  • 17
1

In my case, the problem was caused by the hosting provider I was using blocking http packets addressed to their IP block that originated from within their IP block. Un-frickin-believable!!!

Jeff
  • 2,095
  • 25
  • 18
0

For a couple of days I was totally blocked on this. I'm very very new to networking/vms but was keen to try set it up myself instead of paying a hosting company to do it for me.

Context

I'm rebuilding the server side for an app that uses php routines to return various bits of data from internal sources as well as external APIs for a map based app. I have started an Oracle VM instance and have installed/set up Apache and php. All running totally fine, until one of my php routines tries to execute a cURL. I start implementing error logging to find that I don't even get a message - just '7', despite implementation being very similar to the above. My php routine accessing an internal file for data was running successfully so I was fairly sure it wasn't an Apache or php issue. I also checked my Apache error logs, nothing telling.

Solution

I nearly gave up - there's talk on disabling SELinux above and in other articles, I tried that and it did work for my purposes, but here's a really good article on why you shouldn't disable SELinux https://www.electronicdesign.com/technologies/embedded-revolution/article/21807408/dont-do-it-disabling-selinux

If temporarily disabling it works and like me you don't want to do this (but it confirms that SELinux is blocking you!), I found a neat little command that actually prints out any SELinux issues in a more readable fashion:

sealert -a /var/log/audit/audit.log

This returned the following:


found 1 alerts in /var/log/audit/audit.log
--------------------------------------------------------------------------------

SELinux is preventing php-fpm from name_connect access on the tcp_socket port 443.

Great, I now get a bit more information than just '7'. Reading further down, I can see it actually makes suggestions:

*****  Plugin catchall_boolean (24.7 confidence) suggests   ******************

If you want to allow httpd to can network connect
Then you must tell SELinux about this by enabling the 'httpd_can_network_connect' boolean.

Do
setsebool -P httpd_can_network_connect 1

This has been mentioned further above but now I have a bit more context and an explanation as to what it does. I run the command, and I'm in business. Furthermore, my SELinux is still set to enforcing, meaning my machine is more secure.

There are many other suggestions logged out, if you're blocked it might be worth logging out/checking out /var/log/audit/audit.log.

cfynes
  • 63
  • 4
0

Execute the command on your terminal setsebool -P httpd_can_network_connect on

0

If you white try from your browser and show message like "curl error 7: failed to connect to 172...**: permission denied" then try from terminal like "http://172 ****". If it working from terminal then run this command.

sudo setsebool httpd_can_network_connect 1

And try from you browser again. Hope will work. Worked fro me.

Lokman Hosen
  • 342
  • 5
  • 6