← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 5 of 24

PHP cURL Introduction

What is cURL?

cURL gives PHP the ability to act as an HTTP client, letting server-side scripts fetch data from or send data to other web services -- essential for anything that talks to an external API.

Example: What is cURL?

php
<?php
echo "cURL lets PHP act as an HTTP client to talk to other web services.";
echo "\n" . (function_exists('curl_init') ? "cURL extension is available" : "cURL not available");
?>

Basic GET Request

A basic request follows a fixed pattern: curl_init() opens a session, curl_setopt() configures the target URL and options, curl_exec() sends the request, and curl_close() releases the resources afterward.

Example: Basic GET Request

php
<?php
$ch = curl_init("https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "Request sent, response length: " . strlen($response ?: "");
?>

Handling Response Headers

Setting CURLOPT_RETURNTRANSFER to true tells cURL to hand the response back as a string your script can inspect, rather than printing it directly to the page -- almost always what you want when consuming an API.

Example: Handling Response Headers

php
<?php
$ch = curl_init("https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "Response returned as a string instead of printed directly";
?>

Sending POST Requests

Sending a POST request means setting CURLOPT_POST to true and passing your form fields as an array (or query string) via CURLOPT_POSTFIELDS, mirroring what a browser does when submitting a form.

Example: Sending POST Requests

php
<?php
$ch = curl_init("https://example.com/api");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ["name" => "Alice"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
echo "POST request sent with form fields";
?>

Error Handling in cURL

Network calls can fail for many reasons -- timeouts, DNS issues, refused connections -- so checking curl_error() and curl_errno() after every request lets you handle those failures gracefully instead of silently continuing with no data.

Example: Error Handling in cURL

php
<?php
$ch = curl_init("https://nonexistent.invalid");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo "cURL error: " . curl_error($ch);
}
curl_close($ch);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.