PHP cURL Introduction
In this page:
$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
// 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");
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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 ?: "");
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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";
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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";
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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);
?>
Login to try C/C++/Java/PHP code in the editor
- Forgetting
CURLOPT_RETURNTRANSFER, socurl_execprints the response instead of returning it. - Not checking
curl_errorwhencurl_execreturns false. - Disabling SSL verification to make errors go away, which makes requests insecure.
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser