**对比$_POST、$GLOBALS['HTTP_RAW_POST_DATA']和file_get_contents('php://input')

最近在开发微信接口,又学到了一些新的技术点,今天就把学到的关于接收数据的技术点给简单的罗列下。

[php] view plain copy
 
 print?
  1. public function __construct($token, $wxuser = ''){  
  2.         $this -> auth($token, $wxuser) || exit;  
  3.         if(IS_GET){  
  4.             echo($_GET['echostr']);  
  5.             exit;  
  6.         }else{  
  7.             $xml = file_get_contents("php://input");  
  8.             $xml = new SimpleXMLElement($xml);  
  9.             $xml || exit;  
  10.             foreach ($xml as $key => $value){  
  11.                 $this -> data[$key] = strval($value);  
  12.             }  
  13.         }  
  14.     }  

上述代码是截取的一个片段,意思为把接收到的微信传过来的xml解析为数组。其中有一处file_get_contents('php://input'),后经查证,微信给开发者账号填写的url发送的是xml数据,但PHP默认只识别application/x-www.form-urlencoded标准的数据类型,对text/xml的内容无法解析为$_POST数组,因此会保留原型,可以交给file_get_contents(‘php://input’)接收,也可以用$GLOBALS['HTTP_RAW_POST_DATA']。

如,传过来的xml为

[php] view plain copy
 
 print?
  1. <xml>  
  2. <ToUserName><![CDATA[ebyben1413005325]]></ToUserName>  
  3. <FromUserName><![CDATA[ga_6281708af4c6]]></FromUserName>  
  4. <CreateTime>1413341614</CreateTime>  
  5. <MsgType><![CDATA[text]]></MsgType>  
  6. <Content><![CDATA[首页]]></Content>  
  7. <MsgId>1234567890123456</MsgId>  


解析过后为

[php] view plain copy
 
 print?
  1. Array  
  2. (  
  3.     [ToUserName] => ebyben1413005325  
  4.     [FromUserName] => ga_6281708af4c6  
  5.     [CreateTime] => 1413341614  
  6.     [MsgType] => text  
  7.     [Content] => 首页  
  8.     [MsgId] => 1234567890123456  
  9. )  

php://input 允许读取 POST 的原始数据。和$GLOBALS['HTTP_RAW_POST_DATA'] 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。同时两者皆不能用于接收enctype="multipart/form-data"形式的数据。

最后再说下$_SERVER['REQUEST_METHOD']这个变量,用过ThinkPHP的朋友应该在代码中使用类似IS_GET、IS_AJAX这种代码吧,追溯下源码,就可以看到

[php] view plain copy
 
 print?
  1. define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);  
  2. define('IS_GET',        REQUEST_METHOD =='GET' ? true : false);  
  3. define('IS_POST',       REQUEST_METHOD =='POST' ? true : false);  
  4. define('IS_PUT',        REQUEST_METHOD =='PUT' ? true : false);  
  5. define('IS_DELETE',     REQUEST_METHOD =='DELETE' ? true : false);  
  6. define('IS_AJAX',       ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) ? true : false);  


原来仅仅就用了这个变量,就达到效果。

原文地址:https://www.cnblogs.com/kenshinobiy/p/5387888.html