if (!function_exists('CurlPost')) {
/**
* CURL POST请求
* @param $url
* @param $data
* @param $header
* @param bool $isSsl
* @return bool|string
* @throws Exception
*/
function CurlPost($url, $data, $header = [], $isSsl = false, $certs = ['apiclient_cert' => '', 'apiclient_key' => '', 'cacert' => ''])
{
$ch = curl_init();
$timeout = 600;
if (!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if ($isSsl) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);//证书检查
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
// curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).'/../cert/apiclient_cert.pem');
curl_setopt($ch, CURLOPT_SSLCERT, $certs['apiclient_cert']);
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
// curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).'/../cert/apiclient_key.pem');
curl_setopt($ch, CURLOPT_SSLCERT, $certs['apiclient_key']);
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'pem');
// curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).'/../cert/cacert.pem');
curl_setopt($ch, CURLOPT_SSLCERT, $certs['cacert']);
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
$reponse = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception(curl_error($ch), 0);
} else {
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (200 !== $httpStatusCode) {
throw new Exception($reponse, $httpStatusCode);
}
}
curl_close($ch);
return $reponse;
}
}
if (!function_exists('CurlPostFile')) {
/**
* $uri 数据接收地址
* $fileContent 二进制数据流
* CURL 数据流形式上传文件(发送数据流到指定地址)
* 思路使用CURLFile发送数据流,所以需要先将二进制数据写入临时文件,然后再发送临时文件,最后删除临时文件
*/
function CurlPostFile($uri, $fileContent) {
//必须用个载体来存储成文件让后使用CURLFile来进行数据流的发送
$fileTemp = "/temp/".time().".txt";
file_put_contents($fileTemp, $fileContent);
$body = ['file'=>new CURLFile($fileTemp, '', 'file')];
$relData = CurlPost($uri, $body);
@unlink($fileTemp);
return $relData;
}
}