How to use cURL to implement Get and Post requests in PHP

PHP中文网
Release: 2023-02-28 09:26:02
Original
28792 people have browsed it

1. introduction to curl

curl is a tool that uses url syntax to transfer files and data. it supports many protocols, such as http, ftp, telnet, etc. the best part is that php also supports the curl library. this article will introduce some advanced features of curl and how to use it in php.

2. basic structure

before learning about more complex features, let's take a look at the basic steps of setting up a curl request in php:

(1) initialization curl_init()

(2) set variables curl_setopt()

the most important thing is that all mysteries are here. 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 obtain the results curl_exec()

(4) release the curl handle curl_close()

3.curl implements get and post

3.1 get method implementation

//初始化
  $ch = curl_init();
  //设置选项,包括url
  curl_setopt($ch, curlopt_url, "http://www.learnphp.cn");
  curl_setopt($ch, curlopt_returntransfer, 1);
  curl_setopt($ch, curlopt_header, 0);
  //执行并获取html文档内容
  $output = curl_exec($ch);
  //释放curl句柄
  curl_close($ch);
  //打印获得的数据
  print_r($output);
Copy after login

3.2 post method implementation

 $url = "http://localhost/web_services.php";
  $post_data = array ("username" => "bob","key" => "12345");
  $ch = curl_init();
  curl_setopt($ch, curlopt_url, $url);
  curl_setopt($ch, curlopt_returntransfer, 1);
  // post数据
  curl_setopt($ch, curlopt_post, 1);
  // post的变量
  curl_setopt($ch, curlopt_postfields, $post_data);
  $output = curl_exec($ch);
  curl_close($ch);
  //打印获得的数据
  print_r($output);
Copy after login

the data obtained in the above method is in json format and is interpreted into an array using the json_decode function.

$output_array = json_decode($output,true);
Copy after login

if you use json_decode($output) to parse, you will get object type data.

the above isusing curl in php get and post request methods's content. for more related content, please pay attention to the php chinese website (www.php.cn)!

Related labels:
source:php.cn
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