Home >Backend Development >PHP Tutorial >PHP uses cURL to implement Get and Post requests

PHP uses cURL to implement Get and Post requests

coldplay.xixi
coldplay.xixiforward
2020-07-13 17:34:018325browse

PHP uses cURL to implement Get and Post requests

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()

##   (4) Release the cURL handle


 

curl_close()

Let’s take a look at the specific implementation:

1.

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);

2.

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:

PHP programming from entry to proficiency

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!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete