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
Release: 2023-04-09 07:50:02
forward
8309 people have browsed it

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template