It was only until recently I discovered the PHP: cURL Library. I’ve been using homegrown functions for fetching HTTP requests, but with the cURL it’s not as much a hassle as it used to be. Remember that the cURL isn’t a PHP standard, and you need to install the extension.
The basic functions
I do have a tendency to forget the most basic cURL functions, so I’ve decided to make a quick post here I can use for references my self. It’s basically a small cURL tutorial.
I’ll start out with listing, a few basic functions, sorted in the order in which you use them.
Function | Description |
curl_init | This creates a curl handle, which is passed with the rest of the functions. You can set the URL as an argument to this function, although I prefer to use the curl_setopt function. |
curl_setopt | Sets the options of the cURL handle (returned from curl_init), an option could be the URL, POST vars, header and so on. There’s many options, so refer to the constants list in the PHP manual. |
curl_exec | Execute your cURL with all the settings. Depending on the CURLOPT_RETURNTRANSFER option, it will return the content or, true or false. |
curl_close | Free up the handle when you’re done.. |
Simple HTTP get
This will use HTTP to call a website, and get the content. Basically this is just a file_get_contents, except you have all the extra options cURL give you:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php // 1) Create the curl handle: $ch = curl_init(); // 2) Set the options you want for the current handle: curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 3) Retrieve the data: $data = curl_exec($ch); // 4) Close up: curl_close($ch); var_dump($data) ?> |
<HTML>
…
</HTML>
Like mentioned we could use var_dump(file_get_contents(“http://www.example.com”)) to get the exact same output, but as an added bonus (on top of the vast set of options) cURL actually performs better than FGC. Read more »