Master curl_setopt: Configure PHP cURL Requests Like a Pro
This guide explains the PHP curl_setopt() function, covering its syntax, parameters, return value, and a complete example that demonstrates configuring a cURL session to perform a GET request with URL, method, timeout, and response handling, helping developers master HTTP requests in PHP.
curl_setopt() is a crucial PHP cURL extension function that sets options for a cURL session, allowing configuration of URL, request method, timeout, and other parameters.
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 demonstrates using curl_setopt() to send a GET request to a specified URL and retrieve the response.
// Initialize cURL session
$ch = curl_init();
// Set the 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 the request
$response = curl_exec($ch);
// Check for failure
if ($response === FALSE) {
echo "Request failed: " . curl_error($ch);
} else {
// Process response data
echo $response;
}
// Close the cURL session
curl_close($ch);Explanation
First, curl_init() creates a cURL handle ($ch). Then curl_setopt() configures options such as CURLOPT_URL, CURLOPT_HTTPGET, CURLOPT_RETURNTRANSFER, and CURLOPT_TIMEOUT. curl_exec() executes the request, curl_error() retrieves error information if needed, and curl_close() ends the session.
Summary
curl_setopt() is an essential function in the PHP cURL extension that lets developers configure various request options—including URL, method, timeout, and response handling—to send and receive HTTP requests efficiently.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
