如何通过PHP发送带有pem证书的curl请求?
问题描述:
我的Apache服务器中有一个php脚本,必须向合作伙伴的服务器发送curl请求。
合作伙伴给我一个.pem文件,我必须附加到我对它的api的每次调用。
I have a php script in my Apache server that have to send a curl request to a partner's server. Partner give me a .pem file that I have to attach to every call I do to its api.
我的php脚本如下:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLCERT, "test.pem" );
curl_setopt($ch,CURLOPT_SSLCERTTYPE,"PEM");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_POST, True);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);
if(!$result)
{
echo "Curl Error: " . curl_error($ch);
}
else
{
echo "Success: ". $result;
}
curl_close($ch);
它返回:
Curl错误:无法设置私钥文件:'test.pem'type PEM
Curl Error: unable to set private key file: 'test.pem' type PEM
pem文件,并说它没有密码短语
Consider that it sends me .pem file and says "it has no passphrase"
答
我认为你需要使用 tmpfile()和 stream_get_meta_data 。
$pemFile = tmpfile();
fwrite($pemFile, "test.pem");//the path for the pem file
$tempPemPath = stream_get_meta_data($pemFile);
$tempPemPath = $tempPemPath['uri'];
curl_setopt($ch, CURLOPT_SSLCERT, $tempPemPath);
资料来源:这个答案在SO 帮助我有类似的问题。
Source: This answer here in SO helps me with similar problem.