PHP cURL学习笔记

介绍

cURL是一个非常常用的 PHP 库,它可以让我们通过 URL 来进行各种网络操作,例如发送 HTTP 请求、FTP 上传文件等。本文将会介绍 PHP 中 cURL 的基础知识和实际应用。

基础知识

  • 初始化 cURL : 使用 curl_init() 函数初始化一个 curl handle。
  • 设置 URL : 使用 curl_setopt() 函数设置要访问的 URL。
  • 执行请求 : 使用 curl_exec() 函数执行 cURL 请求。
  • 获取结果 : 使用 curl_getinfo() 函数获取请求的结果信息,使用 curl_error() 函数获取请求过程中遇到的错误信息,使用 curl_close() 函数关闭 curl handle。

实例

发送 GET 请求

以下是一个使用 cURL 发送 GET 请求的实例:

phpCopy Code
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.example.com/api/path?key=value"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $info = curl_getinfo($ch); $error = curl_error($ch); curl_close($ch); if ($error) { echo "cURL Error: {$error}"; } else { echo "Response: {$output}"; }

这段代码会发送一个 GET 请求到 https://www.example.com/api/path?key=value,然后将响应结果输出到屏幕。

发送 POST 请求

以下是一个使用 cURL 发送 POST 请求的实例:

phpCopy Code
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.example.com/api/path"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, "key1=value1&key2=value2"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $info = curl_getinfo($ch); $error = curl_error($ch); curl_close($ch); if ($error) { echo "cURL Error: {$error}"; } else { echo "Response: {$output}"; }

这段代码会发送一个 POST 请求到 https://www.example.com/api/path,POST 数据为 key1=value1&key2=value2,然后将响应结果输出到屏幕。

设置请求头

以下是一个使用 cURL 设置请求头的实例:

phpCopy Code
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.example.com/api/path"); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxx' )); curl_setopt($ch, CURLOPT_POSTFIELDS, '{"key": "value"}'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $info = curl_getinfo($ch); $error = curl_error($ch); curl_close($ch); if ($error) { echo "cURL Error: {$error}"; } else { echo "Response: {$output}"; }

这段代码会发送一个 POST 请求到 https://www.example.com/api/path,并设置了请求头 Content-Type: application/jsonAuthorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxx,POST 数据为 {"key": "value"},然后将响应结果输出到屏幕。

结论

PHP 中的 cURL 提供了很多 HTTP 请求相关的函数和选项,我们可以根据具体的需求来选择相应的方法。同时,需要注意请求过程中可能出现的错误及处理方式。