在PHP开发的过程中经常需要发送POST请求,POST相比GET要安全很多,而且传输的数据量也较大。下面总结下PHP发送POST请求的几种常用方式,分别使用curl、file_get_content来实现POST请求和传递参数。
1、curl实现PHP POST请求和传递参数。
$data=array("参数1"=>"参数值1","参数2"=>"参数值2");//post参数
$url="https://www.only4.work";
$ch = curl_init();//创建连接
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//将数组转换为URL请求字符串,否则有些时候可能服务端接收不到参数
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); //接收服务端范围的html代码而不是直接浏览器输出
curl_setopt($ch, CURLOPT_HEADER, false);
$responds = curl_exec($ch);//接受响应
curl_close($ch);//关闭连接2、file_get_content实现PHP POST请求和传递参数
$data=array("参数1"=>"参数值1","参数2"=>"参数值2");//post参数
$url="https://www.only4.work";
$content = http_build_query($data);
$length = strlen($content);
$options = array(
'http' => array(
'method' => 'POST',
'header' =>
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-length: $length \r\n",
'content' => $content
)
);
file_get_contents($url, false, stream_context_create($options));参考:http://www.leixuesong.cn/2667
本站文章除注明转载/出处外,均为原创,若要转载请务必注明出处。转载后请将转载链接通过邮件告知我站,谢谢合作。本站邮箱:admin@only4.work
尊重他人劳动成果,共创和谐网络环境。点击版权声明查看本站相关条款。
 QQ登录
QQ登录 微博登录
微博登录 GitHub登录
GitHub登录