- Original: PHP based Curl Quick Start
- English Original: Http://net.tutsplus.com/tutorial ... for-mastering-curl/
- Original Author: Burak Guzel
CURL is a tool that uses URL syntax to transfer files and data, and supports many protocols, such as HTTP, FTP, Telnet, and so on. Best of all, PHP also supports CURL libraries. This article will introduce some of the advanced features of CURL and how to use it in PHP.
Why do you use CURL?
Yes, we can get the content of the webpage by other means. Most of the time, because I want to be lazy, I use simple PHP functions directly:
$content = file_get_contents ("http://www.nettuts.com");
Or
$lines = File ("http://www.nettuts.com");
Or
ReadFile (http://www.nettuts.com);
However, this approach lacks flexibility and effective error handling. Also, you can't use it to do some difficult tasks-such as processing coockies, validation, form submission, file uploads, and so on.
Reference:
CURL is a powerful library that supports many different protocols, options, and provides various details about URL requests.
Basic structure
Before you learn more complex features, take a look at the basic steps in creating a Curl request in PHP:
- Class
- Setting variables
- Execute and get results
- Release Curl handle
1. Class
$ch = Curl_init ();
2. Setting options, including URLs
curl_setopt ($ch, Curlopt_url, "http://www.nettuts.com");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 0);
3. Execute and get the contents of the HTML document
$output = curl_exec ($ch);
4. Release Curl handle
Curl_close ($ch);
The second step (i.e. curl_setopt ()) is the most important, and all mysticism is here. There is a long string of curl parameters that can be set to specify the details of the URL request. It may be difficult to read it all at once and understand it, so today we'll just try the more common and useful options.
Check for errors
You can add an error-checking statement (although this is not required):
// ...
$output = curl_exec ($ch);
if ($output = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}
// ...
Note that when comparing, we use "= = False" instead of "= = False". Because we have to distinguish between null output and Boolean value false, the latter is the real error.