Mastering PHP curl_setopt: Set Options for HTTP Requests
This article explains how to use PHP's curl_setopt function to configure cURL sessions, covering its syntax, parameters, return values, and a complete example that demonstrates sending a GET request with custom options and handling the response.
cURL is a powerful PHP extension for sending and receiving HTTP requests. The curl_setopt() function is essential for setting options on a cURL session.
Syntax
bool curl_setopt ( resource $ch , int $option , mixed $value )Parameter Explanation
$ch: The cURL handle created by curl_init(). $option: The specific 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 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 the response as a string instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set a timeout of 30 seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Execute the cURL request
$response = curl_exec($ch);
// Check if the request failed
if ($response === FALSE) {
echo "Request failed: " . curl_error($ch);
} else {
// Process the response data
echo $response;
}
// Close the cURL session
curl_close($ch);Explanation
First, curl_init() creates a cURL handle ( $ch). Then curl_setopt() configures several options: CURLOPT_URL sets the target URL, CURLOPT_HTTPGET sets the request method to GET, CURLOPT_RETURNTRANSFER tells cURL to return the response as a string, and CURLOPT_TIMEOUT defines a 30‑second timeout.
Calling curl_exec() executes the request. If it fails, curl_error() provides the error message; otherwise, the response can be processed. Finally, curl_close() releases the cURL handle.
Summary
The curl_setopt() function is a vital part of the PHP cURL extension, allowing developers to configure various aspects of an HTTP request such as URL, method, timeout, and response handling. By mastering curl_setopt(), you can efficiently send and receive HTTP requests within PHP code.
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.
