How to implement get and post requests using curl in PHP _php tips

Source: Internet
Author: User
Tags curl

1.cURL Introduction

CURL is a tool that uses URL syntax to transfer files and data, and supports many protocols, such as HTTP, FTP, Telnet, and so on. Best of all, PHP also supports CURL libraries. This article will introduce some of the advanced features of CURL and how to use it in PHP.

2. Basic structure

Before you learn more complex features, take a look at the basic steps in creating a Curl request in PHP:

(1) initialization

Curl_init ()

(2) Set Variable

curl_setopt (). Most important, all the occult are here. There is a long string of curl parameters that can be set to specify the details of the URL request. It may be difficult to read it all at once and understand it, so today we'll just try the more common and useful options.

(3) Execute and obtain the result

Curl_exec ()

(4) Release curl handle

Curl_close ()

3.cURL implement GET and post

3.1 Get Mode implementation

Copy Code code as follows:

$ch = Curl_init ();

Setting options, including URLs
curl_setopt ($ch, Curlopt_url, "");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 0);

Execute and get the contents of the HTML document
$output = curl_exec ($ch);

Release Curl handle
Curl_close ($ch);

Print the obtained data
Print_r ($output);

3.2 Post Method implementation
Copy Code code as follows:

$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 data
curl_setopt ($ch, Curlopt_post, 1);
Post's variable
curl_setopt ($ch, Curlopt_postfields, $post _data);

$output = curl_exec ($ch);
Curl_close ($ch);

Print the obtained data
Print_r ($output);


The data obtained in the above method is in JSON format and the Json_decode function is used to interpret the array.

$output _array = Json_decode ($output, true);

If you use Json_decode ($output) parsing, you will get data of type object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.