Home  >  Article  >  Backend Development  >  A simple example of using the php curl_setopt() function to capture web pages and POST data

A simple example of using the php curl_setopt() function to capture web pages and POST data

怪我咯
怪我咯Original
2017-05-19 11:29:551935browse

The previous article explained to you the concept of the curl_setopt function in PHP. It is an extension library of PHP. Using the curl_setopt() function can easily and quickly crawl web pages (can be used for collection) , using it needs to be configured and enabled in php.ini.

extension=php_curl.dll

A simple example of using the php curl_setopt() function to capture web pages and POST data

Now you can use the php curl_setopt function, so let’s look at the first usage first:

1. A crawled web page A simple case:

The code is as follows:

<?php

// 创建一个新cURL资源  
$ch = curl_init();

// 设置URL和相应的选项  
curl_setopt($ch, CURLOPT_URL, "http://www.php.cn/");
curl_setopt($ch, CURLOPT_HEADER, false);

// 抓取URL并把它传递给浏览器  
curl_exec($ch);

//关闭cURL资源,并且释放系统资源  
curl_close($ch); 
?>

The above example code captures a domain name of http://www.php. cn/ web page, the code execution result is as follows:

A simple example of using the php curl_setopt() function to capture web pages and POST data


##2. POST data case:

When using curl, there will often be data interaction, so it is more important.

 <?php  
     $ch = curl_init();  
     /*在这里需要注意的是,要提交的数据不能是二维数组或者更高 
     *例如array(&#39;name&#39;=>serialize(array(&#39;tank&#39;,&#39;zhang&#39;)),&#39;sex&#39;=>1,&#39;birth&#39;=>&#39;20101010&#39;) 
     *例如array(&#39;name&#39;=>array(&#39;tank&#39;,&#39;zhang&#39;),&#39;sex&#39;=>1,&#39;birth&#39;=>&#39;20101010&#39;)这样会报错的*/ 
     $data = array(&#39;name&#39; => &#39;test&#39;, &#39;sex&#39;=>1,&#39;birth&#39;=>&#39;20101010&#39;);  
     curl_setopt($ch, CURLOPT_URL, &#39;http://localhost/mytest/curl/upload.php&#39;);  
     curl_setopt($ch, CURLOPT_POST, 1);  
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
     curl_exec($ch);  
     ?>

In the upload.php file, print_r($_POST); can use curl to grab the content Array output by upload.php ( [name] => test [sex] => ; 1 [birth] => 20101010 )

【Recommended related articles】

1.

php curl_setopt function concept and usage examples

2 .

Detailed explanation of usage examples of PHP curl_exec function

The above is the detailed content of A simple example of using the php curl_setopt() function to capture web pages and POST data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn