背景
工作中經(jīng)常需要對接第三方系統(tǒng)醒颖,經(jīng)常遇到 curl 參數(shù)報錯異常的問題雇锡。
curl post 傳遞參數(shù)
$url = 'xxx.kangxuanpeng.com/xx/server';
$data = ['param' => 'test'];
$ch = curl_init($url);
$head_array = array('application/x-www-form-urlencoded');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($req_array));
curl_setopt($ch, CURLOPT_HTTPHEADER, $head_array);
$response = curl_exec($ch);
參數(shù)經(jīng)過 http_build_query()
轉(zhuǎn)換成 key 對應(yīng) value 值的綁定發(fā)送到第三方,問題就在于 http_build_query()
進(jìn)行的符號加密贬蛙。
問題定位
如果參數(shù)無特殊符號雨女, http_build_query()
正常加密:
$param = ['param' => 'test', 'blog' => 'HongXunPan'];
echo http_build_query($param);
//param=test&blog=HongXunPan
但是如果參數(shù)中有特殊參數(shù)的話,就不一樣了:
$param = ['param' => 'test','blog' => 'HongXunPan', 'url' => 'https://blog.kangxuanpeng.com/'阳准,'time' => '2020-06-18 22:00:00'];
echo http_build_query($param);
//param=test&blog=HongXunPan&url=https%3A%2F%2Fblog.kangxuanpeng.com%2F&time=2020-06-18+22%3A00%3A00
然而恰好是對 /
符號的轉(zhuǎn)換氛堕,第三方系統(tǒng)無法識別。
解決方法
問題找到了就很好定位了野蝇,只需要自己實現(xiàn)一個方法手動進(jìn)行拼接即可讼稚。
function transferArrayToSignString($req_array)
{
$str = '';
foreach ($req_array as $key => $value) {
if ($str != '') {
$str .= '&';
}
$str .= $key.'='.$value;
}
return $str;
}
大功告成:
$param = ['param' => 'test','blog' => 'HongXunPan', 'url' => 'https://blog.kangxuanpeng.com/'筑凫,'time' => '2020-06-18 22:00:00'];
echo http_build_query($param);
//param=test&blog=HongXunPan&url=https%3A%2F%2Fblog.kangxuanpeng.com%2F&time=2020-06-18+22%3A00%3A00
echo transferArrayToSignString($param);
//param=test&blog=HongXunPan&url=https://blog.kangxuanpeng.com/&time=2020-06-18 22:00:00