-

PHP发送POST请求的常用方式

PHP

在PHP开发的过程中经常需要发送POST请求,POST相比GET要安全很多,而且传输的数据量也较大。下面雷雪松就带大家一起总结下PHP发送POST请求的几种常用方式,分别使用curl、file_get_content来实现POST请求和传递参数。

1、curl实现PHP POST请求和传递参数。
[cc lang=”php” escaped=”true”]$data=array(“username”=>”raykaeso”,”name”=>”雷雪松”);//post参数
$url=”https://www.xuesongboke.cn”;
$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);//关闭连接[/cc]

2、file_get_content实现PHP POST请求和传递参数
[cc lang=”php” escaped=”true”]$data=array(“username”=>”raykaeso”,”name”=>”雷雪松”);//post参数
$url=”https://www.xuesongboke.cn”;
$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));[/cc]

来源:PHP发送POST请求的常用方式

3 评论 “PHP发送POST请求的常用方式

    免费小说在线阅读 评论:
    2016年7月5日 下午10:42

    留名!支持!博主技术真好

    Penn 评论:
    2017年2月8日 上午10:10

    因为工作原因,最近打算学习下php,博主有什么建议吗?

    吾读 评论:
    2019年5月10日 下午7:54

    非常精彩的文章,引人入胜,痛快淋漓。感谢楼主分享。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注