当前位置: 代码网 > it编程>编程语言>Php > PHP中为什么使用file_get_contents("php://input")接收微信通知

PHP中为什么使用file_get_contents("php://input")接收微信通知

2024年06月02日 Php 我要评论
微信用户和公众号产生交互的过程中,用户的某些操作会使得微信服务器通过事件推送的形式,通知到开发者在开发者中心处设置的服务器地址(回调url),从而开发者可以获取到该信息。php中为什么会使用file_

微信用户和公众号产生交互的过程中,用户的某些操作会使得微信服务器通过事件推送的形式,通知到开发者在开发者中心处设置的服务器地址(回调url),从而开发者可以获取到该信息。php中为什么会使用file_get_contents("php://input")来接收呢?为什么有些场景file_get_contents("php://input")会接收不到呢?

php用file_get_contents("php://input")或者$http_raw_post_data可以接收xml数据,

file_get_contents()

file_get_contents() 函数把整个文件读入一个字符串中。

php://input

php://input 是个可以访问请求的原始数据的只读流。 post 请求的情况下,最好使用 php://input 来代替 $http_raw_post_data,因为它不依赖于特定的 php.ini 指令。 而且,这样的情况下 $http_raw_post_data 默认没有填充, 比激活 always_populate_raw_post_data 潜在需要更少的内存。 enctype="multipart/form-data" 的时候 php://input 是无效的。

php://input使用范围

1、 读取post数据

2、不能用于multipart/form-data类型

$http_raw_post_data

$http_raw_post_data是php内置的一个全局变量。它用于,php在无法识别的content-type的情况下,将post过来的数据原样地填入变量$http_raw_post_data。它同样无法读取content-type为multipart/form-data的post数据。需要设置php.ini中的always_populate_raw_post_data值为on,php才会总把post数据填入变量$http_raw_post_data。

php://input、$http_raw_post_data、$_post、$_get区别

1、get提交时,不会指定content-type和content-length,它表示http请求body中的数据是使用http的post方法提交的表单数据,并且进行了urlencode()处理。

2、 post提交时,content- type取值为application/x-www-form-urlencoded时,也指明了content-length的值,php会将http请求body相应数据会填入到数 组$_post,填入到$_post数组中的数据是进行urldecode()解析的结果。

3、php://input数据,只要content-type不为 multipart/form-data(该条件限制稍后会介绍)。那么php://input数据与http entity body部分数据是一致的。该部分相一致的数据的长度由content-length指定。 
4、仅当content-type为application/x-www-form-urlencoded且提交方法是post方法时,$_post数据与php://input数据才是”一致”(打上引号,表示它们格式不一致,内容一致)的。其它情况,它们都不一致。 
5、php://input读取不到$_get数据。是因为$_get数据作为query_path写在http请求头部(header)的path字段,而不是写在http请求的body部分。

接收和发送xml的php示例

php示例:接收xml

接收xml数据,并转化为array数组。

<?php
$xmldata = file_get_contents("php://input");
$obj = simplexml_load_string($xmldata,"simplexmlelement", libxml_nocdata);
$json = json_decode(json_encode($obj),true);

php示例:发送xml

<?php
$xml = '<xml>xmldata</xml>';//要发送的xml
$url = 'http://***.php';//接收xml地址
$header = 'content-type: text/xml';//定义content-type为xml
$ch = curl_init(); //初始化
curl curl_setopt($ch, curlopt_url, $url);//设置链接
curl_setopt($ch, curlopt_returntransfer, 1);//设置是否返回信息
curl_setopt($ch, curlopt_httpheader, $header);//设置http头
curl_setopt($ch, curlopt_post, 1);//设置为post方式
curl_setopt($ch, curlopt_postfields, $xml);//post数据
$response = curl_exec($ch);//接收返回信息
if(curl_errno($ch)){//出错则显示错误信息
    print curl_error($ch);
}
curl_close($ch); //关闭curl链接
echo $response;//显示返回信息
?>

到此这篇关于php中为什么使用file_get_contents("php://input")接收微信通知的文章就介绍到这了,更多相关php中file_get_contents("php://input")接收微信通知内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com