下面是一个简单的PHP函数,用于发送POST和GET请求,并且可以传输数组或者字符串,可选传入header请求头:
function curlRequest($url, $method = 'GET', $data = array(), $headers = array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不验证https证书 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不验证https证书 if ($method == 'POST') { curl_setopt($ch, CURLOPT_POST, true); if (is_array($data)) { $data = http_build_query($data); } curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } else if ($method == 'GET') { if (is_array($data)) { $data = http_build_query($data); } if (!empty($data)) { $url .= '?' . $data; } } if (!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $result = curl_exec($ch); curl_close($ch); return $result; }
使用方法:
发送GET请求:
$url = 'http://example.com/api/getData'; $data = array('param1' => 'value1', 'param2' => 'value2'); $headers = array('Authorization: Bearer token123'); $response = curlRequest($url, 'GET', $data, $headers); echo $response;
发送POST请求:
$url = 'http://example.com/api/createOrder'; $data = array('item1' => 'item1value', 'item2' => 'item2value'); $headers = array('Authorization: Bearer token123', 'Content-Type: application/json'); $response = curlRequest($url, 'POST', $data, $headers); echo $response;