Mastering PHP cURL: How to Perform GET and POST Requests

This guide introduces PHP's cURL extension, outlines its basic workflow, and provides clear GET and POST code examples, showing how to configure options, execute requests, handle responses, and decode JSON data into arrays or objects.

21CTO
21CTO
21CTO
Mastering PHP cURL: How to Perform GET and POST Requests

CURL is a command‑line tool that transfers data using URL syntax and supports protocols such as HTTP, FTP and TELNET. PHP provides a cURL extension, allowing developers to perform HTTP requests directly from scripts.

The basic workflow in PHP consists of four steps: initialize with curl_init(), set options via curl_setopt(), execute the request with curl_exec(), and finally close the handle with curl_close(). The most commonly used options include the request URL, return transfer flag, header inclusion, request method and POST fields.

GET request example

$ch = curl_init();
curl_setopt($ch, curlOPT_URL, "http://www.eer3.com");
curl_setopt($ch, curlOPT_RETURNTRANSFER, 1);
curl_setopt($ch, curlOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);

POST request example

$url = "http://localhost/web_services.php";
$post_data = array("username" => "uname", "key" => "123456");
$ch = curl_init();
curl_setopt($ch, curlOPT_URL, $url);
curl_setopt($ch, curlOPT_RETURNTRANSFER, 1);
curl_setopt($ch, curlOPT_POST, 1);
curl_setopt($ch, curlOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);

When the response is JSON, it can be decoded into an associative array with json_decode($output, true), or into an object by omitting the second parameter.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JSONHTTPPHPcURLgetPOST
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.