Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl from php takes more time than curl via putty

Tags:

php

curl

I am trying to send a curl request to googleapis, to fetch a users information. When I use a php script to send the cURL request, it takes 5 seconds to complete, yet, when I try to send the same request directly from the server with a curl command, the result return instantly.

Here's the php script I use:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v2/userinfo");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer '.$accessToken));
$output=curl_exec($ch);

And here is the curl command I've used with putty:

curl --header "Authorization: Bearer xxxxxx" https://www.googleapis.com/oauth2/v2/userinfo

What could be the problem?

NOTE: The php script runs on the same server from which I emmited the curl command via putty

NOTE 2: Could this be some kind of DNS lookup problem? At first, running this same command via command line also took around 5 seconds to complete, because www.googleapis.com was not in our DNS server. Since then, we added it manually, and the command line function runs much quicker. What kind of DNS information is PHP using, if I update the DNS info on the server, does it automatically gets updated for PHP too?

NOTE 3: dig www.googleapis.com returns the following:

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.37.rc1.el6_7.4 <<>> www.googleapis.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 5273
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.googleapis.com. IN A

;; ANSWER SECTION:
www.googleapis.com. 1536 IN CNAME googleapis.l.google.com.
googleapis.l.google.com. 172 IN A 216.58.218.170

;; Query time: 0 msec
;; SERVER: 10.0.80.11#53(10.0.80.11)
;; WHEN: Wed Sep 9 14:35:04 2015
;; MSG SIZE rcvd: 89

like image 371
Adam Baranyai Avatar asked Oct 30 '22 19:10

Adam Baranyai


1 Answers

Found the answer to the problem here:

https://stackoverflow.com/a/17816201/2691879

Setting this option, solves the problem:

curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

I still don't really understand why and how is this working/happening, so if someone cares to explain it to me in another answer, together with the above solution, I will mark that as the correct answer.

like image 119
Adam Baranyai Avatar answered Nov 02 '22 11:11

Adam Baranyai