萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php curl中x

php curl中x

下面我們一起來看一篇關於php 中x-www-form-urlencoded與multipart/form-data 方式 Post 提交數據詳解,希望文章能夠對各位有所幫助哦。

multipart/form-data 方式

post的curl庫,模擬post提交的時候,默認的方式 multipart/form-data ,這個算是post提交的幾個基礎的實現方式。

$postUrl = '';
$postData = array(
    'user_name'=>$userName,
    'identity_no'=>$idCardNo
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $postUrl);
curl_setopt($curl, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$r = curl_exec($curl);
curl_close($curl);

print_r($r);

想用的可以直接拿去試試

x-www-form-urlencoded方式

php的curl庫進行post提交還是蠻方便的。但是提交方式不同,contentType 不同導致你的api是否能接收到數據也是個變數,這裡來個簡單的實例。

$postUrl = '';
$postData = array(
    'user_name'=>$userName,
    'identity_no'=>$idCardNo
);
$postData = http_build_query($postData);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $postUrl);
curl_setopt($curl, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$r = curl_exec($curl);
curl_close($curl);

print_r($r);

關鍵一段代碼是

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

copyright © 萬盛學電腦網 all rights reserved