Usage of the curl_init function in PHP

Source: Internet
Author: User
Tags how to use curl

Copy codeThe Code is as follows:
$ Ch = curl_init ();
$ C_url = 'HTTP: // www.baidu.com ';
$ C_url_data = "product _ & type =". $ type ."";
Curl_setopt ($ ch, CURLOPT_URL, $ c_url );
Curl_setopt ($ ch, CURLOPT_POST, 1 );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ c_url_data );
Echo $ result = curl_exec ($ ch );
Curl_close ($ ch );
Unset ($ ch );

Use Curl in PHP
Posted September 14 th, 2008 belongs to PHP
Address: http://www.phpit.net/article/using-curl-php copyright statement: Signature-non-commercial use-deduction prohibited 2.0
Abstract:
This article describes the php_curl library and how to better use php_curl.
Introduction
You may encounter the following problem in your PHP script code: How can I get content from other sites? Here are several solutions. The simplest thing is to use the fopen () function in php, but the fopen function does not have enough parameters to use. For example, if you want to build a "web crawler ", to define the crawler client description (IE, firefox), you can obtain the content through different request methods, such as POST and GET. These requirements cannot be implemented using the fopen () function.
To solve the problem we raised above, we can use the PHP extension library-Curl. This extension library is usually in the installation package by default, and you can obtain the content of other sites, you can also do something else.
Note: The two codes must be supported by the php_curl extension library. View phpinfo (). If curl support is enabled, the curl library is supported.
1. Enable curl library support for PHP in Windows:
Open php. ini and remove the; sign before extension = php_curl.dll.
2. Enable curl library support for PHP in Linux:
Add-with-curl after./configure during PHP Compilation
In this article, let's take a look at how to use the curl library and its other functions. However, next we will start with the most basic usage.
Basic usage:
Step 1: Use the curl_init () function to create a new curl session. The Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
?>
We have successfully created a curl session. If you need to obtain the content of a URL, pass a URL to the curl_setopt () function in the next step. The Code is as follows:
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.google.com /");
?>
After finishing the previous step, the preparation of curl is complete, curl will get the content of the URL site and print it out. Code:
// Grab URL and pass it to the browser
Curl_exec ($ ch );
?>
Finally, close the current curl session
// Close curl resource, and free up system resources
Curl_close ($ ch );
?>
Let's take a look at the completed instance code:
Copy codeThe Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.google.nl /");
// Grab URL and pass it to the browser
Curl_exec ($ ch );
// Close curl resource, and free up system resources
Curl_close ($ ch );
?>

We have just obtained the content of another site and then automatically output it to the browser. Do we have other ways to organize the information and control the output content? No problem at all. In the curl_setopt () function parameter, if you want to obtain the content but do not output it, use the CURLOPT_RETURNTRANSFER parameter and set it to a non-0 value/true !, Complete code can be found:
Copy codeThe Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.google.nl /");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
// Grab URL, and return output
$ Output = curl_exec ($ ch );
// Close curl resource, and free up system resources
Curl_close ($ ch );
// Replace 'Google 'with 'phpit'
$ Output = str_replace ('Google ', 'phpit', $ output );
// Print output
Echo $ output;
?>

In the above two instances, you may notice that different results can be obtained by setting different parameters of the curl_setopt () function, which is exactly why curl is powerful, let's take a look at the meanings of these parameters.
CURL-related options:
If you have read the curl_setopt () function in the php manual, you can note that the following long parameter list cannot be described one by one. For more information, see the PHP manual, here we only introduce common and some parameters.
The first interesting parameter is CURLOPT_FOLLOWLOCATION. When you set this parameter to true, curl will obtain the redirection path in a deeper level based on any redirection command. For example: when you try to get a PHP page and there is a jump code in the PHP page, curl will get the content from http: // new_url instead of returning the jump code. The complete code is as follows:
Copy codeThe Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.google.com /");
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, true );
// Grab URL, and print
Curl_exec ($ ch );
?>

If Google sends a redirection request, the preceding example continues to retrieve the content based on the redirected URL. Two options related to this parameter are CURLOPT_MAXREDIRS and CURLOPT_AUTOREFERER.
The parameter CURLOPT_MAXREDIRS option allows you to define the maximum number of redirect requests. If this parameter is exceeded, the system will no longer obtain its content. If CURLOPT_AUTOREFERER is set to true, the curl will automatically add a Referer header in each jump link. It may not be very important, but it is very useful in some cases.
The parameter described in the next step is CURLOPT_POST, which is a very useful feature because it allows you to do this for POST requests instead of GET requests, which actually means you can submit
Other forms of pages do not need to be filled in the form. The following example shows what I mean:
Copy codeThe Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http: // projects/phpit/content/using % 20 curl % 20php/demos/handle_form.php ");
// Do a POST
$ Data = array ('name' => 'Dennis ', 'surname' => 'pallett ');
Curl_setopt ($ ch, CURLOPT_POST, true );
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data );
// Grab URL, and print
Curl_exec ($ ch );
?>
And the handle_form.php file:
Echo 'form variables I got Ed :';
Echo '';
Print_r ($ _ POST );
Echo '';
?>

As you can see, this makes it really easy to submit forms, which is a great way to test all your forms without filling them at all times.
The CURLOPT_CONNECTTIMEOUT parameter is usually used to set the curl request link time. This is a very important option. If you set this time period too short, the curl request may fail.
However, if you set it too long, the PHP script may die. One option related to this parameter is CURLOPT_TIMEOUT, which is used to set the time required for curl execution. If you set this small value, it may be incomplete on the downloaded webpage because it takes some time for them to download.
The last option is CURLOPT_USERAGENT, which allows you to customize the client name of the request, for example, webspilder or IE6.0. the sample code is as follows:
Copy codeThe Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http:// SC .jb51.net /");
Curl_setopt ($ ch, CURLOPT_USERAGENT, 'My M web spider/100 ′);
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, true );
// Grab URL, and print
Curl_exec ($ ch );
?>

Now we have introduced the most interesting parameter. Next we will introduce a curl_getinfo () function to see what it can do for us.
Obtain the page information:
The curl_getinfo () function allows us to obtain various information on the accept page. You can edit this information by setting the second parameter of the option, and you can also pass an array. As shown in the following example:
Copy codeThe Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.google.com ");
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, true );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
Curl_setopt ($ ch, CURLOPT_FILETIME, true );
// Grab URL
$ Output = curl_exec ($ ch );
// Print info
Echo '';
Print_r (curl_getinfo ($ ch ));
Echo '';
?>

Most of the returned information is the request itself, such as the time it takes for the request, the header file information returned, and some page information, such as the size of the page content and the last modification time.
Those are all about the curl_getinfo () function. Now let's take a look at its actual usage.
Actual use:
The first purpose of the curl library is to check whether a URL page exists. We can check the code returned by the URL request to determine whether 404 indicates that this page does not exist. Let's look at some examples:
Copy codeThe Code is as follows:
// Create a new curl resource
$ Ch = curl_init ();
// Set URL and other appropriate options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.google.com/does/not/exist ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
// Grab URL
$ Output = curl_exec ($ ch );
// Get response code
$ Response_code = curl_getinfo ($ ch, CURLINFO_HTTP_CODE );
// Not found?
If ($ response_code = '000000 ′){
Echo 'page doesn \'t exist ';
} Else {
Echo $ output;
}
?>

Other users may create an automatic Checker to verify whether the page for each request exists.
We can use the curl library to write web spider similar to google, or other web spider. This article is not about how to write a web spider, so we didn't talk about any details about web spider. However, in the future, PHPit will introduce how to use curl to construct a web spider.
Conclusion:
In this article, I have demonstrated how to use the curl library in php and most of its options.
For the most basic task, you only want to get a Web page. You may not need the CURL library. However, if you want to do anything more advanced, you may want to use the curl library.
In the near future, I will tell you how to build your own web spider, similar to Google's web spider, so stay tuned to phpit.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.