PHP中使用cURL实现Get和Post请求的方法
封面图
•
2025-10-20
•
PHP
223
0
0
0
在 PHP 中,`cURL` 是一个非常强大的库,用于发送 HTTP 请求(包括 GET 和 POST)。下面是使用 `cURL` 实现 GET 和 POST 请求的示例代码。 --- ## 一、GET 请求 ```php <?php // 初始化 cURL 会话 $ch = curl_init(); // 设置请求 URL curl_setopt($ch, CURLOPT_URL, "https://example.com/api/data"); // 设置为 GET 请求(默认就是 GET) curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行请求 $response = curl_exec($ch); // 检查是否有错误 if ($response === false) { echo 'cURL Error: ' . curl_error($ch); } else { echo 'Response: ' . $response; } // 关闭 cURL 会话 curl_close($ch); ?> ``` --- ## 二、POST 请求 ```php <?php // 初始化 cURL 会话 $ch = curl_init(); // 设置请求 URL curl_setopt($ch, CURLOPT_URL, "https://example.com/api/submit"); // 设置为 POST 请求 curl_setopt($ch, CURLOPT_POST, true); // 设置 POST 数据(可以是字符串或数组) $postData = [ 'username' => 'testuser', 'password' => '123456' ]; // 将数据编码为 application/x-www-form-urlencoded 格式 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 设置返回结果不直接输出,而是返回字符串 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行请求 $response = curl_exec($ch); // 检查是否有错误 if ($response === false) { echo 'cURL Error: ' . curl_error($ch); } else { echo 'Response: ' . $response; } // 关闭 cURL 会话 curl_close($ch); ?> ``` --- ## 三、发送 JSON 数据的 POST 请求 如果你需要发送 JSON 数据: ```php <?php $data = [ 'name' => 'John', 'age' => 30 ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://example.com/api/json"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if ($response === false) { echo 'cURL Error: ' . curl_error($ch); } else { echo 'Response: ' . $response; } curl_close($ch); ?> ``` --- ## 四、常用选项说明 | 参数 | 说明 | |------|------| | `CURLOPT_URL` | 要请求的 URL | | `CURLOPT_RETURNTRANSFER` | 是否将结果作为字符串返回(而不是直接输出) | | `CURLOPT_POST` | 是否为 POST 请求 | | `CURLOPT_POSTFIELDS` | POST 请求的数据 | | `CURLOPT_HTTPHEADER` | 设置 HTTP 请求头(如 Content-Type) | | `curl_error()` | 获取错误信息 | --- 如有其他需求(如设置超时、添加 headers、处理 cookies 等),也可以继续问我。
上一篇:
PHP file_get_contents设置超时处理方法
下一篇:
php用$_POST
标题录入,一次不能超过6条
留言
评论