Using Curl in PHP

Source: Internet
Author: User
Tags array copy curl php file php and php script resource response code
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);

Using Curl in PHP
Posted September 14th, 2008 belongs to PHP
Original (English) address: http://www.phpit.net/article/using-curl-php Copyright statement: Signature-non-commercial use-Prohibition of Deduction 2.0
Summary:
This article focuses on Php_curl library knowledge and teaches you how to better use Php_curl.
Brief introduction
You might have a problem with writing PHP script code: How do you get content from other sites? Here are a few solutions; The simplest is to use the fopen () function in PHP, but the fopen function does not have enough parameters to use, for example, when you want to build a "web crawler", you want to define a crawler's client description (Ie,firefox), get content through different requests, such as post,get, etc. these requirements are not possible with the fopen () function.
To solve the problem we raised above, we can use the PHP extension library-curl, which is usually the default in the installation package, you can get the content of other sites, you can do something else.
Note: These two pieces of code need the support of the Php_curl extension library to view phpinfo (), and if curl support enabled, the Curl library is supported.
1, Windows under the PHP Open Curl Library Support:
Open the php.ini and remove the Extension=php_curl.dll from the front.
2, Linux under the PHP Open Curl Library Support:
When compiling PHP, add –with-curl after the./configure.
In this article, let's look at how to use the Curl library and see its other uses, but next, we'll start with the most basic usage
Basic usage:
In the first step, we create a new curl session through the function Curl_init (), the code is as follows:
Create a new Curl resource
$ch = Curl_init ();
?>
We have successfully created a curl session, if you need to get the content of a URL, then take the next step, pass a URL to the curl_setopt () function, code:
Set URL and other appropriate options
curl_setopt ($ch, Curlopt_url, "http://www.google.com/");
?>
Finish the last step of work, curl preparation work done, curl will get the content of the URL site, and print out. Code:
Grab URL and pass it to the browser
Curl_exec ($ch);
?>
Finally, close the current Curl session
Close Curl Resource.
Curl_close ($ch);
?>
Now 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.
Curl_close ($ch);
?>

We have just put the content of another site, get over to automatically output to the browser, we have no other way to organize the acquisition of information, and then control the content of its output? Absolutely no problem, in the curl_setopt () function parameters, if you want to get content but do not output, use the Curlopt_returntransfer parameter, and set to a value of not 0/true!, complete code see:
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.
Curl_close ($ch);
Replace ' Google ' with ' phpit '
$output = Str_replace (' Google ', ' phpit ', $output);
Print output
Echo $output;
?>

In the 2 examples above, you may notice that you can get different results by setting the different parameters of the function curl_setopt (), which is why curl is powerful, so let's look at the implications of these parameters.
Curl Related options:
If you've looked at the curl_setopt () function in the PHP manual, you'll notice that the long list of arguments below it is not possible, and you can look at the PHP manual for more information, and here are just some of the commonly used and some parameters.
The first interesting argument is curlopt_followlocation, and when you set this argument to True, curl will get a more deep access to the path according to any redirect command, for example: When you try to get a PHP page, Then this PHP page has a jump code, curl will get the content from the Http://new_url, rather than return 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 turn request, the example above will continue to fetch content based on the URL of the jump, and the two options associated with this parameter are Curlopt_maxredirs and Curlopt_autoreferer.
The parameter Curlopt_maxredirs option allows you to define the maximum number of jump requests, exceeding this number of times to no longer acquire their content. If Curlopt_autoreferer is set to True, Curl automatically adds Referer headers in each jump link, which may not be important, but is useful in certain cases.
The next argument is Curlopt_post, which is a very useful feature because it allows you to do POST requests instead of GET requests, which actually means that you can submit
Other forms of the page, do not need to actually fill 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%20curl%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 received: ';
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 and not to fill them in all the time.
Parameter curlopt_connecttimeout is often used to set the time when a curl is trying to request a link, which is a very important option, and if you set this time too short, it may cause the curl request to fail.
But if you set it up too long, maybe the php script will die. One option associated with this parameter is Curlopt_timeout, which is used to set the time requirement for curl to allow execution. If you set this a very small value, it may lead to downloading the pages that are not complete because they take a while to download.
The last option is Curlopt_useragent, which allows you to customize the client name of the request, such as 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 Custom Web spider/0.1′ ');
curl_setopt ($ch, curlopt_followlocation, true);
Grab URL, and print
Curl_exec ($ch);
?>

Now that we've introduced one of the most interesting parameters, let's introduce a curl_getinfo () function to see what it can do for us.
To get information about a page:
function Curl_getinfo () allows us to get all kinds of information on the receiving page, you can edit the information by setting the second parameter of the option, you can also pass an array form. Just like 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 information returned is the request itself, such as: This request takes time, returns the header file information, and of course there are some page information, such as the size of the page content, the last modified time.
Those are all about the Curl_getinfo () function, now let's look at its actual use.
Actual use:
The first purpose of the Curl Library is to see if a URL page exists, and we can judge by looking at the code returned by this URL, for example, 404 represents 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 = = ' 404′) {
Echo ' Page doesn\ ' t exist ';
} else {
Echo $output;
}
?>

Other users may be creating an automatic inspector to verify that each requested page exists.
We can use the Curl Library to write web spiders like Google (Web spider), or other web spiders. This article is not about how to write a Web spider, so we don't talk about any details about web spiders, but later on in Phpit will introduce curl to construct a web spider.
Conclusion:
In this article I have shown how to use the Curl Library in PHP and most of its options.
For the most basic task, just want to get a page, you may not need the curl library, but once you want to do anything slightly 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, please look forward 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.