一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php curl中x-www-form-urlencoded与multipart/form-data 方式 Post 提交数据详解

时间:2022-06-24 15:10:51 编辑:袖梨 来源:一聚教程网

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'));

热门栏目