[英]PHP Curl request with CRT, PEM, PFX and Passphrase
我在 PHP 中使用了以下代碼。 我搜索了幾個站點並在 curl function 下工作。 在 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, true);
curl_setopt($curl, CURLOPT_CAINFO, $pemfile);
curl_setopt($curl, CURLOPT_SSLCERT, $pemfile);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_POST, 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);
?>
我知道我很晚才回復,但是 CURL 請求確實支持帶密鑰的 PFX 文件格式,下面是相同的代碼
Curl::to($url)
->withHeaders($headers)
->withContentType('application/json')
->withOption('HTTP_VERSION', 'CURL_HTTP_VERSION_1_1')
->withOption('SSLCERTTYPE', 'P12')
->withOption('SSLCERT', <Path of the Certificate>)
->withOption('SSLKEYPASSWD', <passphrase used to create pfx>)
->withOption('HTTP_VERSION', 'CURL_HTTP_VERSION_1_1')
->withData(json_encode($body))
->withTimeout(30)
->post();
使用 curl 請求發送 PFX 文件的主要關鍵是告訴 CURL 您正在為此目的傳遞 P12 格式文件,我們正在使用:
'SSLCERTTYPE','P12'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.