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

PHP cURL Introduction

cURL lets PHP visit other websites for you, like sending a helper to fetch something from another shop. It can ask for data or send some along and bring back the reply.
Syntax
php
$ch = curl_init("https://example.com/path");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   // return response as a string
$response = curl_exec($ch);
curl_close($ch);

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
// Print "cURL lets PHP act as an HTTP client to talk to other web services." to the output
echo "cURL lets PHP act as an HTTP client to talk to other web services.";
// Print `"\n" . (function_exists('curl_init') ? "cURL extension is available" : "cURL not available")` to the output
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
// Declare `$ch`, set to `curl_init("https://example.com")`
$ch = curl_init("https://example.com");
// Call `curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Declare `$response`, set to `curl_exec($ch)`
$response = curl_exec($ch);
// Call `curl_close($ch)`
curl_close($ch);
// Print `"Request sent, response length: " . strlen($response ?: "")` to the output
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
// Declare `$ch`, set to `curl_init("https://example.com")`
$ch = curl_init("https://example.com");
// Call `curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Declare `$response`, set to `curl_exec($ch)`
$response = curl_exec($ch);
// Call `curl_close($ch)`
curl_close($ch);
// Print "Response returned as a string instead of printed directly" to the output
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
// Declare `$ch`, set to `curl_init("https://example.com/api")`
$ch = curl_init("https://example.com/api");
// Call `curl_setopt($ch, CURLOPT_POST, true)`
curl_setopt($ch, CURLOPT_POST, true);
// Call `curl_setopt($ch, CURLOPT_POSTFIELDS, ["name" => "Alice"])`
curl_setopt($ch, CURLOPT_POSTFIELDS, ["name" => "Alice"]);
// Call `curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Call `curl_exec($ch)`
curl_exec($ch);
// Call `curl_close($ch)`
curl_close($ch);
// Print "POST request sent with form fields" to the output
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
// Declare `$ch`, set to `curl_init("https://nonexistent.invalid")`
$ch = curl_init("https://nonexistent.invalid");
// Call `curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)`
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Call `curl_setopt($ch, CURLOPT_TIMEOUT, 2)`
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
// Declare `$response`, set to `curl_exec($ch)`
$response = curl_exec($ch);
// Check whether `curl_errno($ch)`
if (curl_errno($ch)) {
    // Print `"cURL error: " . curl_error($ch)` to the output
    echo "cURL error: " . curl_error($ch);
}
// Call `curl_close($ch)`
curl_close($ch);
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting CURLOPT_RETURNTRANSFER, so curl_exec prints the response instead of returning it.
  2. Not checking curl_error when curl_exec returns false.
  3. Disabling SSL verification to make errors go away, which makes requests insecure.

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.