The curl_setopt function is a core tool used to set cURL request options. In PHP, when using cURL to make HTTP requests, it is often necessary to configure different aspects of the request, such as setting the request method, request header, request body, etc. curl_setopt can easily accomplish these configurations.
$ch = curl_init(); // initializationcURLSession
curl_setopt($ch, CURLOPT_URL, "https://gitbox.net/api/v1/resource"); // Set requestedURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set the return data to a string instead of direct output
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Set request timeout
In this example, we use curl_setopt to set multiple options for the cURL session, such as URL, return method, and timeout limit.
The curl_close function is used to close an initialized cURL session and release related resources. After we complete the cURL operation, calling curl_close is a good habit. It can effectively free up system resources and avoid memory leaks.
curl_close($ch); // closurecURLSession
In actual development, curl_setopt and curl_close are often used together. First, we use curl_setopt to configure the relevant options for the request, then use curl_exec to execute the request, and finally use curl_close to close the session.
// initializationcURLSession
$ch = curl_init();
// Set requestedURL
curl_setopt($ch, CURLOPT_URL, "https://gitbox.net/api/v1/resource");
// Set the return data to a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set request timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Execute a request and get a response
$response = curl_exec($ch);
// Error handling
if(curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch);
}
// closurecURLSession
curl_close($ch);
// Output response data
echo $response;
Initialize a cURL session : Initialize a cURL session through curl_init() .
Set cURL options : Configure the request URL, return method, timeout time, etc. through curl_setopt .
Execute request : Execute the request via curl_exec and save the response to the variable.
Error handling : Use curl_errno to check whether an error has occurred. If an error occurs, use curl_error to output the error message.
Close the cURL session : Finally, call curl_close to close the cURL session and release the resource.