问题描述
我在 PHP 中使用了以下代码。我搜索了几个站点并在 curl 函数下进行了此操作。在 Postman 添加证书(设置-> SSL 验证设置)中,它通过传递 CRT、PEM、PFX 和密码短语来工作。但是当我打算在 PHP 代码中使用它时,它不起作用。
function curlapi() {
$url = "https://exampleurl.com/service";
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$headers = array(
"Content-Type: application/json",);
$data = '{"login":"test_login","password":"test_password"}';
$pemFile = tmpfile();
fwrite($pemFile,"/folder/path/test_file.pem");//the path for the pem file
$tempPemPath = stream_get_Meta_data($pemFile);
$tempPemPath_uri = $tempPemPath['uri'];
curl_setopt($curl,CURLOPT_SSLCERT,$tempPemPath_uri);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
//for debug only!
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
$resp = curl_exec($curl);
echo "<pre>";
print_r(curl_getinfo($curl)) . '<br/>';
echo curl_errno($curl) . '<br/>';
echo curl_error($curl) . '<br/>';
curl_close($curl);
print_r($resp);
exit;
}
curlapi();
解决方法
最后,我担心在 CURL 请求中没有使用 CRT、PFX 和密码短语。它仅适用于 PEM 文件路径。
<?php $data = array(
"PageNumber" => 1,"PageSize" => 100,"SearchCriteria" => array(
"keyword" => "Getvalue"
));
$pemfile = getcwd()."/assets/path/file.pem"; $curl = curl_init($url);
$method = "POST";
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,CURLOPT_CAINFO,$pemfile);
curl_setopt($curl,CURLOPT_SSLCERT,CURLOPT_CUSTOMREQUEST,$method);
curl_setopt($curl,true);
$headers = array(
"Content-Type: application/json",);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($data));
$resp = curl_exec($curl);
/*echo "<pre>";
print_r(curl_getinfo($curl)) . '<br/>';
echo curl_errno($curl) . '<br/>';
echo curl_error($curl) . '<br/>';*/
curl_close($curl);
?>