使用cURL库可以很方便地实现PHP中的GET和POST请求。
GET请求:
// 创建cURL资源 $ch = curl_init(); // 设置URL和其他cURL选项 curl_setopt($ch, CURLOPT_URL, "http://www.example.com/api/endpoint?param1=value1¶m2=value2"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 发送请求并获取响应 $response = curl_exec($ch); // 关闭cURL资源 curl_close($ch); // 处理响应 if ($response === false) { // 请求失败 } else { // 请求成功,处理$response数据 }
POST请求:
// 创建cURL资源 $ch = curl_init(); // 设置URL和其他cURL选项 curl_setopt($ch, CURLOPT_URL, "http://www.example.com/api/endpoint"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); // 设置POST数据 $data = https://www.yisu.com/ask/array('param1' => 'value1', 'param2' => 'value2' ); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // 发送请求并获取响应 $response = curl_exec($ch); // 关闭cURL资源 curl_close($ch); // 处理响应 if ($response === false) { // 请求失败 } else { // 请求成功,处理$response数据 }
以上代码中,我们首先通过curl_init()
函数创建了一个cURL资源,然后使用curl_setopt()
函数设置了URL和其他选项,如是否返回响应内容、是否使用POST方法等。接着,通过curl_exec()
函数发送请求并获取响应。最后,使用curl_close()
函数关闭cURL资源,不再使用时可以释放内存。
对于POST请求,我们还需要使用curl_setopt()
函数设置POST数据,可以使用http_build_query()
函数将关联数组转换为URL编码的字符串。