File_get_contents () vs curl to call API with PHP

According to the description of the Google Custom Search API, you can call it using the GET verb of the REST interface, for example, using an example:

GET https://www.googleapis.com/customsearch/v1?key=INSERT-YOUR-KEY&cx=017576662512468239146:omuauf_lfve&q=lectures 

I configure my API key and user search system, and when I inserted my test request directly into my browser, it worked fine, and I received a JSON file for me.

Then I tried to call the API from my PHP code using:

 $json = file_get_contents("$url") or die("failed"); 

Where $ url was the same that worked in the browser, but my PHP code was dying when trying to open it.

After that I tried with curl and it worked. The code was as follows:

 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $body = curl_exec($ch); 

Questions

  • How come the get_contents () file did not work and curl did?
  • Can I use fsocket for this?
+8
rest php
source share
3 answers

Question 1:

First you should check the ina allow_url_fopen , AFAIK is the only reason file_get_contents() should not work. It may also be deprecated safe_mode .

Oh, based on your comment, you should add http:// to the URL when using the file system , a wrapper that tells php that you need to use the http request, without the function you need to open ./google.com (same as google.txt ).

Question 2:

Yes, you can build almost any cURL request with sockets.

My personal opinion is that you should stick to cURL because:

  • timeout settings
  • handles all possible HTTP states
  • simple and detailed configuration (no need for detailed knowledge of HTTP headers)
+11
source share

file_get_contents probably rewrite your request after receiving the IP address, getting the same as:

 file_get_contents("xxx.yyy.www.zzz/app1",...) 

Many servers will refuse access if you go through the IP addressing in the request.
With cURL, this problem does not exist. It resolves the host name, leaving a request as it is installed, so the server is not rude in response.
This may be the "reason".

+4
source share

1) Why do you use quotation marks when calling file_get_contents ?

2) As noted in the comment, file_get_contents requires allow_url_fopen to enable php.ini .

3) You can use fsockopen , but you will have to process the HTTP requests / responses manually, which would reinvent the wheel when you have cURL. The same goes for socket_create .

4) Regarding the title of this question: cURL may be more customizable and useful for dealing with complex HTTP transactions than file_get_contents . Although it should be noted that working with contexts allows you to make many settings for your calls to file_get_contents . However, I think cURL is even more perfect, since it gives you, for example, the ability to work with multiple parallel handlers .

+3
source share

All Articles