Using curl_setopt() in PHP cURL: Syntax, Parameters, Return Value, and Example
This article explains the PHP cURL extension's curl_setopt() function, covering its syntax, parameter meanings, boolean return value, and provides a complete example that demonstrates setting URL, request method, response handling, timeout, error checking, and session closure.
cURL is a powerful PHP extension for sending and receiving HTTP requests, and the curl_setopt() function is essential for configuring a cURL session.
Syntax
The syntax of curl_setopt() is:
bool curl_setopt ( resource $ch , int $option , mixed $value )Parameter Explanation
$ch: the 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 uses curl_setopt() to send a GET request to a specified URL and retrieve 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
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Execute request
$response = curl_exec($ch);
// Check for failure
if ($response === FALSE) {
echo "Request failed: " . curl_error($ch);
} else {
// Process response data
echo $response;
}
// Close cURL session
curl_close($ch);Explanation
The example first creates a cURL handle with curl_init() , then sets options such as CURLOPT_URL , CURLOPT_HTTPGET , CURLOPT_RETURNTRANSFER , and CURLOPT_TIMEOUT . The request is executed with curl_exec() , errors are retrieved via curl_error() , and the session is closed with curl_close() .
Summary
The curl_setopt() function is a key part of the PHP cURL extension, allowing developers to configure various aspects of a cURL session—including URL, request method, timeout, and more—so that HTTP requests can be sent and received easily within PHP code.
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.