CURL ERROR: Recv failure: Connection reset by peer - PHP Curl - php

I'm having this strange error, CURL ERROR: Recv failure: Connection reset by peer
This is how it happens, if I did not connect to the server and all of a sudden trying to connect to the server via CURL in PHP I get the error. When I run the CURL script again the error disappears and then works well the whole time, if I leave the remote server idle for about 30mins or reboot the remote server and try to connect again, I get the error again. So it seems like the connection is idle and then all of sudden the server wakes up and then works and then sleeps again.
This is how my CURL script looks.
$url = Yii::app()->params['pdfUrl'];
$body = 'title='.urlencode($title).'&client_url='.Yii::app()->params['pdfClientURL'].'&client_id='.Yii::app()->params['pdfClientID'].'&content='.urlencode(htmlentities($content));
$c = curl_init ($url);
$body = array(
"client_url"=>Yii::app()->params['pdfClientURL'],
"client_id"=>Yii::app()->params['pdfClientID'],
"title"=>urlencode($title),
"content"=>urlencode($content)
);
foreach($body as $key=>$value) { $body_str .= $key.'='.$value.'&'; }
rtrim($body_str,'&');
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body_str);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT , 20);
$pdf = curl_exec ($c);
$errorCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
$curlInfo = curl_getinfo($c);
$curlError = curl_error($c);
curl_close ($c);
I'm totally out of ideas and solutions, please help, I'll appreciate it!!!
If I verbose the output to see what happens using
curl_setopt ($c, CURLOPT_VERBOSE, TRUE);
curl_setopt($c, CURLOPT_STDERR, $fp);
I get the following
* About to connect() to 196.41.139.168 port 80 (#0)
* Trying 196.x.x.x... * connected
* Connected to 196.x.x.x (196.x.x.x) port 80 (#0)
> POST /serve/?r=pdf/generatePdf HTTP/1.1
Host: 196.x.x.x
Accept: */*
Content-Length: 7115
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
* Recv failure: Connection reset by peer
* Closing connection #0
012 20:23:49 GMT
< Server: Apache/2.2.15 (CentOS)
< X-Powered-By: PHP/5.3.3
< Connection: close
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<
* Closing connection #0
I've added in the following toe remove the default header and still no luck:
curl_setopt ($c, CURLOPT_HTTPHEADER, array( 'Expect:' ) );
> Accept: */* Content-Length: 8414 Content-Type:
> application/x-www-form-urlencoded
>
> * Recv failure: Connection reset by peer
> * Closing connection #0 r: Apache/2.2.15 (CentOS) < X-Powered-By: PHP/5.3.3 < Connection: close < Transfer-Encoding: chunked <
> Content-Type: text/html; charset=UTF-8 <
> * Closing connection #0

Introduction
The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake.
Possible Causes
A. TCP/IP
It might be a TCP/IP issue you need to resolve with your host or upgrade your OS most times connection is closed with remote server before it finished downloading the content resulting in Connection reset by peer.....
B. Kernel Bug
Note that there are some issues with TCP window scaling on some Linux kernels after v2.6.17. See the following bug reports for more information:
https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.17/+bug/59331
https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.20/+bug/89160
C. PHP & CURL Bug
You are using PHP/5.3.3 which has some serious bugs too ... I would advise you to work with a more recent version of PHP and CURL
https://bugs.php.net/bug.php?id=52828
https://bugs.php.net/bug.php?id=52827
https://bugs.php.net/bug.php?id=52202
https://bugs.php.net/bug.php?id=50410
D. Maximum Transmission Unit
One common cause of this error is that the MTU (Maximum Transmission Unit) size of packets travelling over your network connection has been changed from the default of 1500 bytes.
If you have configured a VPN this most likely must changed during configuration
D. Firewall: iptables
If you don't know your way around these guys they can cause some serious issues .. try and access the server you are connecting to check the following
You have access to port 80 on that server
Example
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT`
The Following is at the last line not before any other ACCEPT
Example
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
Check for ALL DROP, REJECT and make sure they are not blocking your connection
Temporary allow all connection as see if it foes through
Experiment
Try on a different server or on a remote server ( So many free cloud hosting online) and test the same script. If it works then my guesses are correct ... You need to update your system
Others Code Related
A. SSL
If Yii::app()->params['pdfUrl'] is a url with https not including proper SSL settings can also cause this error in old version of curl
Resolution: Make sure OpenSSL is installed and enabled then add this to your code
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.
Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.
cURL sometimes having issue with SSL and SSL certificates.
I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.
Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.
Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

I faced same error but in a different way.
When you curl a page with a specific SSL protocol.
curl --sslv3 https://example.com
If --sslv3 is not supported by the target server then the error will be
curl: (35) TCP connection reset by peer
With the supported protocol, error will be gone.
curl --tlsv1.2 https://example.com

So what is the URL that Yii::app()->params['pdfUrl'] gives? You say it should be https, but the log shows it's connecting on port 80... which almost no server is setup to accept https connections on. cURL is smart enough to know https should be on port 443... which would suggest that your URL has something wonky in it like: https://196.41.139.168:80/serve/?r=pdf/generatePdf
That's going to cause the connection to be terminated, when the Apache at the other end cannot do https communication with you on that port.
You realize your first $body definition gets replaced when you set $body to an array two lines later? {Probably just an artifact of you trying to solve the problem} You're also not encoding the client_url and client_id values (the former quite possibly containing characters that need escaping!) Oh and you're appending to $body_str without first initializing it.
From your verbose output we can see cURL is adding a content-length header, but... is it correct? I can see some comments out on the internets of that number being wrong (especially with older versions)... if that number was to small (for example) you'd get a connection-reset before all the data is sent. You can manually insert the header:
curl_setopt ($c, CURLOPT_HTTPHEADER,
array("Content-Length: ". strlen($body_str)));
Oh and there's a handy function http_build_query that'll convert an array of name/value pairs into a URL encoded string for you.
All this rolls up into the final code:
$post=http_build_query(array(
"client_url"=>Yii::app()->params['pdfClientURL'],
"client_id"=>Yii::app()->params['pdfClientID'],
"title"=>$title,
"content"=>$content));
//Open to URL
$c=curl_init(Yii::app()->params['pdfUrl']);
//Send post
curl_setopt ($c, CURLOPT_POST, true);
//Optional: [try with/without]
curl_setopt ($c, CURLOPT_HTTPHEADER, array("Content-Length: ".strlen($post)));
curl_setopt ($c, CURLOPT_POSTFIELDS, $post);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT , 20);
//Collect result
$pdf = curl_exec ($c);
$curlInfo = curl_getinfo($c);
curl_close($c);

This is a firewall issue, if you are using a VMware application, make sure the firewall on the antivirus is turned off or allowing connections.
If this server is on a secure network, please have a look at firewall rules of the server.
Thanks
Ganesh PNS

In my case there was problem in URL. I've use https://example.com - but they ensure 'www.' - so when i switched to https://www.example.com everything was ok. The proper header was sent 'Host: www.example.com'.
You can try make a request in firefox brwoser, persist it and copy as cURL - that how I've found it.

We had the same issue, in making a websocket connection to the Load Balancer.
The issue is in LB, accepting http connection on port 80 and forwarding the request to node (tomcat app on port 8080).
We have changed this to accept tcp (http has been changed as 'tcp') connection on port 80.
So the first handshake request is forwarded to Node and a websocket connection is made successfully on some random( as far as i know, may be wrong) port.
below command has been used to test the websocket handshake process.
curl -v -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost" -H "Origin: http://LB URL:80" http://LB URL
Rebuilt URL to: http:LB URL/
Trying LB URL...
TCP_NODELAY set
Connected to LB URL (LB URL) port 80 (#0)
GET / HTTP/1.1
Host: localhost
User-Agent: curl/7.60.0
Accept: /
Connection: Upgrade
Upgrade: websocket
Origin: http://LB URL:80
Recv failure: Connection reset by peer
Closing connection 0
curl: (56) Recv failure: Connection reset by peer

Related

CURL error: [77] error setting certificate verify locations: using LetsEncrypt certificate

I know this question has been asked in multiple threads and for many situations. I have been searching through these threads for days now. I'm still at a loss. I'm hoping someone here can shed some new light.
I think the question is: What do I need to do to get PHP CURL to use the certificate issued to the web site. In this case, the LetsEncrypt certificate is issued by using CERTBOT. The certificate is valid according to the browsers I have tested with.
My domain is: app.ccgopvt.org
I ran this PHP procedure...
$sslCertPath = "/etc/letsencrypt/live/app.ccgopvt.org/fullchain.pem";
$ch = curl_init( $url );
// Assign CAINFO to the specific SSL Cert ONLY IF it is self-authorized.
curl_setopt( $ch, CURLOPT_CAINFO, $sslCertPath);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 1);
curl_setopt( $ch, CURLOPT_CERTINFO, 1);
curl_setopt( $ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch);
if ( ! ($response)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
$response = "postToURL - CURL error: [$errno] $errstr.";
}
curl_close($ch);
It produced this output:
postToURL - CURL error: [77] error setting certificate verify locations: CAfile: /etc/letsencrypt/live/app.ccgopvt.org/fullchain.pem CApath: /etc/ssl/certs.
My web server is (include version):
Server version: Apache/2.4.25 (Debian)
Server built: 2019-10-13T15:43:54
The operating system my web server runs on is (include version):
Debian GNU/Linux 9 \n \l
My hosting provider, if applicable, is: myself
I can login to a root shell on my machine (yes or no, or I don't know): yes
I'm using a control panel to manage my site (no, or provide the name and version of the control panel): no
The version of my client is (e.g. output of certbot --version or certbot-auto --version if you're using Certbot):
certbot 0.28.0
I can run curl directly from the command line for the same URL and I get a valid response. e.g...
# curl https://app.ccgopvt.org
</head>
<body>
<h1>You have reached the CCGOPVT Admin Pages</h1>
...
This behavior is specific to my web applications. Things were working, and suddenly they weren't. (Yes, of course something changed. I'm just at a loss for what!) The initial setting of $sslCertPath above was NULL. (That's my default setting on other servers.) But that produced the error. The above tries to assign the LetsEncrypt certificate path, but the result is the same.
I'm sure I am missing something basic in my understanding of how CURL uses SSL certificates. Somehow, I think this problem has to do with the interaction of the two. I'm hoping someone here can help.
Thanks in advance,
Ron

PHP CURL suddenly stop working on https request

Until literally a couple of days ago, everything was going well, but now, Curl has stopped working for addresses with HTTPS.
This is the code:
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => array($registation_ids),
'data' => array( "message" => $message,
"title" => $title,
"params" => $params,
"code" =>$code),
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
This code had been running smoothly for over a year. But now it returns this:
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET
/app/test_notifications.
Reason: Error reading from remote server
Apache/2.2.15 (Red Hat) Server at app-servername.rhcloud.com Port 80
However, if in the previous code I remove the s from https:// ... like this http://android.googleapis.com/gcm/send the request is sent without problems, but I can not allow that modification, since I also need access to other addresses that require SSL.
I have also tested with other https addresses, but it is the same result
Searching on the internet I found the solution to update curl, but I'm not sure if that is my solution, since the code executed correctly https requests last week. Anyway I leave here the curl --version response on my server:
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp
Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz
Is there a way to test that, in effect, is a Curl problem? That would help me to know how to find the solution.
I think it's a Google upgrade not a Curl problem.
Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.
GCM Connection Server Reference
HTTP Protocol
XMPP Protocol
Android API Reference
iOS API Reference
Chrome API Reference
Contents
Downstream message syntax
Downstream HTTP messages (JSON)
Notification payload support
Downstream HTTP messages (Plain Text)
Interpreting a downstream message response
Downstream message error response codes
Check https://developers.google.com/cloud-messaging/http-server-ref
Reviewing the problem and comparing my different applications in Openshift I realized that curl in https addresses worked in one of them. I checked the differences using phpinfo() and discovered that, contrary to what the server indicated, in the application that presented the problem, SSL Version was 3.18.1 and not 3.27.1.
Solution: restart the application in openshift and if that does not work, manually update curl. (Restart work for me)

PHP TCP connection to EPP API using SSL certificate authentication

I have tried this upwards and backwards without any success. The national domain registry department has decided to change their entire system to EPP. Their documentation is very poor but to summarize:
Connection via TCP: epptest.ficora.fi port 700
To whitelist for firewall, add IP address and SSL certificate to user account on dashboard (done that)
The dashboard is a total mess. I cannot upload the same certificate to different users, I can't remove users etc. Anyhow, you are supposed to connect to that address and verify yourself using the same SSL certificate in the request (atleast that's what I've understood) but I cannot get it to work. All my requests return:
Error 7: "Failed to connect to epptest.ficora.fi port 700: Timed out"
I've created a login XML based on the documentation which I send out in the POST request.
ini_set('max_execution_time', 300);
set_time_limit(0);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'epptest.ficora.fi');
curl_setopt($curl, CURLOPT_PORT, 700);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($curl, CURLOPT_TIMEOUT, 400);
curl_setopt($curl, CURLOPT_SSLCERT, __DIR__ . '/certificate.crt');
$output = curl_exec($curl);
echo 'Error ' . curl_errno($curl) . ': "' . curl_error($curl) .'"';
curl_close($curl);
The certificate file can be found, I did a file_get_contents() test and reads OK. This is a localhost test on a Windows computer.
Testing the same code on my own (live) server I get:
Error 56: "Recv failure: Connection reset by peer"
I don't know if this sounds stupid or not but does the request have to originate from a server, from an address, where the SSL certificate is in use?
I am at a complete loss with this as to why it doesn't work. Help, anyone?
EDIT
Here's the cURL verbose information:
* About to connect() to epptest.ficora.fi port 700 (#0)
* Trying <ip_address>
* connected
* Connected to epptest.ficora.fi (<ip address>) port 700 (#0)
> POST / HTTP/1.1
Host: epptest.ficora.fi:700
Accept: */*
Content-type: text/xml
Content-length: 146
* upload completely sent off: 146 out of 146 bytes
* additional stuff not fine transfer.c:1037: 0 0
* Recv failure: Connection reset by peer
* Closing connection #0
The answer in the end came to me through another Stackoverflow post. I actually didn't have the private key in the certificate so what I had to do was create a new .pem file (just plain text in any editor) and paste the private key and certificate in it like so:
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE----
-----END CERTIFICATE-----
The certificate is supposed to have the key in it. All I had was them separate. No one actually pointed this out.
HOWEVER! I was not able to make this work in cURL. The response I got was through a PHP-EPP library that uses stream_socket_client() function.
I've seen two kinds of errors from epptest.ficora fi:
Connection timeout indicates the IP address is not allowed to connect.
Connection reset by peer indicates the certificate is invalid.
This weekend all my connections failed with Connection reset by peer. Today (29.8.2016) it started working again, so this was probably a temporary issue. So far I have seen successful authentication with CAcert server certificates and Comodo FreeSSL certificates.
However, an IP address that I enabled two days ago is still blocked. It's possible that their automatic firewall updating every 8 hours is not working as documented and that you'll need to contact Ficora support (fi-domain-tech#ficora.fi) to open the IP.
Also, I don't believe curl supports EPP, so it's probably not useful in this case. (EPP is a custom protocol used over TCP port 700. It's not based on HTTP.)

cURL PHP ERROR: Unknown SSL protocol error in connection

I'm trying to send an Ajax request using cURL PHP but it gives the error
Unknown SSL protocol error in connection
while I'm able to login to same server.
I've tried this
curl_setopt( $ch, CURLOPT_SSLVERSION, 1 );
and Ajax request is something like that
$header = array('Accept' => '*/*',
"X-Requested-With" => "XMLHttpRequest",
"Content-Type" => "application/x-www-form-urlencoded");
$data = array('ClientNumber=999999&OrderClass=ContractOrders&ShowAll=ContractOrders&ShowPerPage=500');
echo $page = Spider::spider($header, 'https://wfs.nursefinders.com/MasterConsole/displayorders.cfm?ShowAll=ContractOrders', 'https://wfs.nursefinders.com/MasterConsole/BuildOrderDisplaySection.cfm', FALSE, $data[0]);
Note in spider function, first argument is header, second is referrer third is url to access, fourth doesn't matter it's for cookie file and fifth is data o post
I'm using UBUNTU 14.10 and cURL Version is curl 7.37.1 according to this command /usr/bin/curl -V
and same as printing by php phpinfo()
Please help
I believe the reason for your problem is that the server you are communicating with does not support your SSL protocol.
There is a page here with information on that: http://blog.techstacks.com/2010/03/3-common-causes-of-unknown-ssl-protocol-errors-with-curl.html
For more direct information, try looking into the API Documentation for the required connection protocol for their server. They may have provided a sample that will connect.
This server is terrible broken. It does not support the most compatible SSLv23 handshake and will just hang if one tries it. It only supports explicit SSL 3.0 or TLS 1.0 handshakes. From looking at the source code of cURL it seems to me, that all variations of enforcing TLS1.0+ will do a SSLv23 handshake, which the server can not do:
-- curl-7.41.0/lib/vtls/openssl.c
1719 default:
1720 case CURL_SSLVERSION_DEFAULT:
1721 case CURL_SSLVERSION_TLSv1:
1722 case CURL_SSLVERSION_TLSv1_0:
1723 case CURL_SSLVERSION_TLSv1_1:
1724 case CURL_SSLVERSION_TLSv1_2:
1725 /* it will be handled later with the context options */
1726 req_method = SSLv23_client_method();
This leaves only the option of using the insecure SSL 3.0, that is
curl_setopt( $ch, CURLOPT_SSLVERSION, 3 );
While I have no PHP to test with, a short test with curl -1 vs. curl -3 on the command line confirms that CURLOPT_SSLVERSION of 1 will not work while 3 should work.

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

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.
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.
“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
If you have tried all the ways and failed, try this one command:
setsebool -P httpd_can_network_connect on
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
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!
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.
Check if port 80 and 443 are blocked. or enter - IP graph.facebook.com and enter it in etc/hosts file
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
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.
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!!!
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.

Categories