March 22, 2012

I have seen many different ways to use CURL in PHP. Which is the "right" one?

Question by Kaoukkos

I have read that CURL is way too fast than File Get Contents and less memory consuming. So, I will go with CURL. I read some articles to find info about it and how to use it properly and efficiently.
The problem is that I found many ways of using CURL, I posted 3 variations below.

My question is which one is the best to use?

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
  $content = curl_exec($ch);


     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $path);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $cache = curl_exec($ch);
     curl_close($ch);


 $ch = curl_init("");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $result = curl_exec($ch);
 curl_close ($ch);

Answer by Rocket Hazmat

It all depends on what options you want. Most of cURL’s options will have some default, which will be set if you do not manually set an option.

For example: CURLOPT_RETURNTRANSFER defaults to FALSE (so setting it to FALSE in your code would be redundant).

Passing a parameter to curl_int is just a shortcut for CURLOPT_URL. The other options all depend on what you want to do.

Here is a list of all the cURL options: http://php.net/manual/en/function.curl-setopt.php

Pick the options you want, exclude those you don’t. There’s no “right” way, just the way that works the way you want.

Answer by Starx

Its like asking,

I have see many ways people code PHP, but which one is right?

There is no correct answer for such question, as everybody is going to have their own opinion about every way.

So, I suggest you read the PHP.net’s manual on CURL and choose the correct method based on your coding style, requirement and construct.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!