PHP cURL: Complete Guide & Usage
cURL (Client URL Library) is a library used for communicating with servers over the internet. In PHP, you can utilize the cURL extension library to send HTTP requests, handle responses, and perform other network operations.
The steps for using the cURL extension library are as follows:
- Check if the cURL extension is installed: You can do this by running the phpinfo() function in PHP to see if cURL is included in the extension list. If it is not installed, you will need to install the extension first.
- Initialize cURL: Use the curl_init() function to start a cURL session. This function will return a cURL handle for further cURL operations.
- Use the curl_setopt() function to configure cURL options for a session, such as the URL, request method, headers, and body.
- Execute a cURL request: Use the curl_exec() function to perform a cURL request. This function will send the request and return the response.
- Handling response: You can utilize the curl_getinfo() function to retrieve some information about a cURL request, such as the response status code, response headers, etc. You can use the curl_error() function to obtain error information related to the cURL request. And finally, you can use the curl_close() function to terminate the cURL session.
Here is an example code using the cURL extension library to send a GET request.
// 初始化 cURL
$curl = curl_init();
// 设置 cURL 选项
curl_setopt($curl, CURLOPT_URL, 'http://example.com/api/users'); // 设置请求的 URL
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 返回响应结果,默认为 true
curl_setopt($curl, CURLOPT_HEADER, false); // 不返回响应头,默认为 false
// 执行 cURL 请求
$response = curl_exec($curl);
// 处理响应
if ($response === false) {
$error = curl_error($curl);
// 处理错误
} else {
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// 处理响应
}
// 关闭 cURL 会话
curl_close($curl);
By using the above code, you can use the cURL extension library to send a GET request and receive the response. Different options can be set as needed to meet specific requirements.