Let’s first look at the basic steps to establish a cURL request in PHP:
(1) Initialization
curl_init()
(2) Set the variable
curl_setopt()
. Most important. There is a long list of cURL parameters that can be set that specify various details of the URL request. It can be difficult to read and understand them all at once, so today we will only try the more common and useful options.
(3) Execute and get the result
curl_exec()
curl_close()
Post implementation (simulation Post request, call interface)
<?php $url = "http://192.168.147.131/index.php/addUser";//你要请求的地址 $post_data = array( "uid" => "1111", "username" => "lunar", "nickname" => "吾独望月", ); $ch = curl_init();//初始化cURL curl_setopt($ch,CURLOPT_URL,$url);//抓取指定网页 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//要求结果为字符串并输出到屏幕上 curl_setopt($ch,CURLOPT_POST,1);//Post请求方式 curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);//Post变量 $output = curl_exec($ch);//执行并获得HTML内容 curl_close($ch);//释放cURL句柄 print_r($output);
Get method to achieve
<?php $url = "http://www.cnblogs.com/blogforly/";//你要请求的地址 $ch = curl_init();//初始化cURL curl_setopt($ch,CURLOPT_URL,$url);//抓取指定网页 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//要求结果为字符串并输出到屏幕上 curl_setopt($ch, CURLOPT_HEADER, 0);//设置header $output = curl_exec($ch);//执行并获得HTML内容 curl_close($ch);//释放cURL句柄 print_r($output);
Related learning recommendations:
The above is the detailed content of PHP uses cURL to implement Get and Post requests. For more information, please follow other related articles on the PHP Chinese website!