Mastering PHP curl_setopt: Syntax, Parameters, and Real-World Example
This guide explains the PHP curl_setopt function, covering its syntax, parameter meanings, return value, and provides a complete example that demonstrates sending a GET request, handling responses, error checking, and closing the cURL session.
Overview
cURL is a powerful PHP extension for sending and receiving HTTP requests. The curl_setopt() function is essential for configuring a cURL session’s options.
Syntax
bool curl_setopt ( resource $ch , int $option , mixed $value )Parameter Explanation
$ch: cURL handle created by curl_init(). $option: the cURL option to set. $value: the value for the option.
Return Value
The function returns a boolean indicating whether the option was set successfully.
Example
The following example sends a GET request to a URL and retrieves the response.
// Initialize cURL session
$ch = curl_init();
// Set URL to request
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
// Set request method to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);
// Return response as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set timeout to 30 seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Execute request
$response = curl_exec($ch);
if ($response === FALSE) {
echo "Request failed: " . curl_error($ch);
} else {
// Process response data
echo $response;
}
// Close cURL session
curl_close($ch);Explanation
The script first creates a cURL handle with curl_init(). It then sets several options: CURLOPT_URL for the target URL, CURLOPT_HTTPGET to use GET, CURLOPT_RETURNTRANSFER to capture the response, and CURLOPT_TIMEOUT for a 30‑second limit. curl_exec() executes the request; on failure curl_error() provides the error message. Finally, curl_close() releases the handle.
Summary
curl_setopt()is a crucial function in the PHP cURL extension that lets developers configure various aspects of an HTTP request, such as URL, method, timeout, and response handling, enabling flexible communication with web services.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
