PHP中怎么用curl发送post请求
在PHP中使用cURL库发送POST请求,可以按照以下步骤:
- 初始化cURL:使用
curl_init()
函数创建一个cURL句柄。
$curl = curl_init();
- 设置请求URL和其他选项:使用
curl_setopt()
函数设置cURL选项,包括请求的URL、请求方法、请求头、请求体等。
$url = 'http://example.com/api';
$data = array('key1' => 'value1', 'key2' => 'value2');
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- 执行请求并获取响应:使用
curl_exec()
函数执行cURL请求,并使用curl_getinfo()
函数获取请求的响应信息。
$response = curl_exec($curl);
$info = curl_getinfo($curl);
// 获取响应状态码
$status_code = $info['http_code'];
- 关闭cURL句柄:使用
curl_close()
函数关闭cURL句柄。
curl_close($curl);
完整的示例代码如下:
$curl = curl_init();
$url = 'http://example.com/api';
$data = array('key1' => 'value1', 'key2' => 'value2');
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$status_code = $info['http_code'];
curl_close($curl);
注意:以上示例中的$data可以是一个URL编码的字符串,或者是一个关联数组。如果是关联数组,cURL会自动将其转换为URL编码的字符串。