PHP通用请求函数sendCurl

function sendCurl($url, $data = null, $method = 'POST') {
	$method = strtoupper($method);
	$start_wdmcurl_time = microtime(true);

	$header = array(' application/x-www-form-urlencoded');
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_FAILONERROR, false);
	// https 请求
	if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	}
	if ($method == 'GET') {
		if ($data && is_array($data) && count($data) > 0) {
			$url .= "?" . http_build_query($data);
		}
		curl_setopt($ch, CURLOPT_URL, $url);
	} elseif ($method == 'POST') {
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		if (is_array($data) && count($data) > 0) {
			curl_setopt($ch, CURLOPT_POST, true);
			$isPostMultipart = false;
			foreach ($data as $k => $v) {
				if ('@' == substr($v, 0, 1)) {
					$isPostMultipart = true;
					break;
				}
			}
			unset($k, $v);
			if ($isPostMultipart) {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			} else {
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
			}
		}
	} elseif (in_array($method, ['PUT', 'DELETE', 'PATCH'])) {
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	$reponse = curl_exec($ch);
	curl_close($ch);
	return $reponse;
}

posted on 2023-08-19 11:29  小馬過河﹎  阅读(39)  评论(0)    收藏  举报

导航