file_get_contents("php://input")的使用方法

本文介绍了PHP中的file_get_contents('php://input')用于获取HTTP请求原始数据,特别是在POST请求中,它比$HTTP_RAW_POST_DATA更有效且不依赖php.ini设置。当Content-Type为multipart/form-data时,php://input无法使用。同时,探讨了$_POST、$HTTP_RAW_POST_DATA、php://input和Content-Type之间的关系,以及如何通过它们处理XML数据和上传文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

$data = 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 是无效的。 
    
 
1, php://input 可以读取http entity body中指定长度的值,由Content-Length指定长度,不管是POST方式或者GET方法提交过来的数据。但是,一般GET方法提交数据 时,http request entity body部分都为空。 
2,php://input 与$HTTP_RAW_POST_DATA读取的数据是一样的,都只读取Content-Type不为multipart/form-data的数据。
学习笔记
 1,Coentent-Type仅在取值为application/x-www-data-urlencoded和multipart/form-data两种情况下,PHP才会将http请求数据包中相应的数据填入全局变量$_POST 
 2,PHP不能识别的Content-Type类型的时候,会将http请求包中相应的数据填入变量$HTTP_RAW_POST_DATA 
 3, 只有Coentent-Type为multipart/form-data的时候,PHP不会将http请求数据包中的相应数据填入php://input,否则其它情况都会。填入的长度,由Coentent-Length指定。 
 4,只有Content-Type为application/x-www-data-urlencoded时,php://input数据才跟$_POST数据相一致。 
 5,php://input数据总是跟$HTTP_RAW_POST_DATA相同,但是php://input比$HTTP_RAW_POST_DATA更凑效,且不需要特殊设置php.ini 
 6,PHP会将PATH字段的query_path部分,填入全局变量$_GET。通常情况下,GET方法提交的http请求,body为空。
 
例子
 1.php用file_get_contents("php://input")或者$HTTP_RAW_POST_DATA可以接收xml数据
 比如:
  getXML.php;//接收XML地址
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!--?php
      $xml = '<xml-->xmldata' ; //要发送的xml
      $url = 'http://localhost/test/getXML.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 ; //显示返回信息
?>
 
 
 2.一个手机上传图片到服务器的小程序
  上传文件
   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!--?php
      //@file phpinput_post.php
      $data = file_get_contents ( 'btn.png' );
      $http_entity_body = $data ;
      $http_entity_type = 'application/x-www-form-urlencoded' ;
      $http_entity_length = strlen ( $http_entity_body );
      $host = '127.0.0.1' ;
      $port = 80;
      $path = '/image.php' ;
      $fp = fsockopen ( $host , $port , $error_no , $error_desc , 30);
      if ( $fp ){
         fputs ( $fp , "POST {$path} HTTP/1.1\r\n" );
         fputs ( $fp , "Host: {$host}\r\n" );
         fputs ( $fp , "Content-Type: {$http_entity_type}\r\n" );
         fputs ( $fp , "Content-Length: {$http_entity_length}\r\n" );
         fputs ( $fp , "Connection: close\r\n\r\n" );
         fputs ( $fp , $http_entity_body . "\r\n\r\n" );
  
         while (! feof ( $fp )) {
          $d .= fgets ( $fp , 4096);
         }
         fclose( $fp );
         echo $d ;
      }
?-->

 
  接收文件
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!--?php
         /**
          *Recieve image data
         **/   
         error_reporting (E_ALL);
  
      function get_contents() {   
         $xmlstr = file_get_contents ( "php://input" );
         $filename =time(). '.png' ;
         if ( file_put_contents ( $filename , $xmlstr )){
          echo 'success' ;
         } else {
          echo 'failed' ;
         }
         }
         get_contents();
?-->

 3.获取HTTP请求原文
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
      * 获取HTTP请求原文
      * @return string
      */
     function get_http_raw() {
      $raw = '' ;
  
      // (1) 请求行
      $raw .= $_SERVER [ 'REQUEST_METHOD' ]. ' ' . $_SERVER [ 'REQUEST_URI' ]. ' ' . $_SERVER [ 'SERVER_PROTOCOL' ]. "\r\n" ;
  
      // (2) 请求Headers
      foreach ( $_SERVER as $key => $value ) {
         if ( substr ( $key , 0, 5) === 'HTTP_' ) {
          $key = substr ( $key , 5);
          $key = str_replace ( '_' , '-' , $key );
  
          $raw .= $key . ': ' . $value . "\r\n" ;
         }
      }
  
      // (3) 空行
      $raw .= "\r\n" ;
  
      // (4) 请求Body
      $raw .= file_get_contents ( 'php://input' );
  
      return $raw ;
}
`file_get_contents('php://input')` 是 PHP 中一个常用的函数,用于读取原始的 HTTP 请求体数据。这个函数在处理 POST 请求时特别有用,尤其是当请求的数据不是表单编码(如 `application/x-www-form-urlencoded` 或 `multipart/form-data`)时,比如 JSON 或 XML 数据。 ### 使用场景 1. **处理 JSON 数据**:当客户端发送 JSON 格式的数据时,可以通过 `file_get_contents('php://input')` 获取原始的 JSON 字符串,然后使用 `json_decode` 将其转换为 PHP 对象或数组。 2. **处理 XML 数据**:类似地,当客户端发送 XML 格式的数据时,可以通过这个函数获取原始的 XML 字符串,然后使用 `simplexml_load_string` 或其他 XML 解析库进行解析。 3. **处理二进制数据**:当需要处理上传的二进制数据(如文件上传)时,也可以使用这个函数获取原始的二进制数据。 ### 示例代码 ```php <?php // 获取原始的 HTTP 请求体数据 $rawData = file_get_contents('php://input'); // 假设客户端发送的是 JSON 数据 $data = json_decode($rawData, true); if ($data === null) { // 处理 JSON 解码错误 http_response_code(400); echo json_encode(['error' => 'Invalid JSON']); exit; } // 处理数据 echo json_encode(['status' => 'success', 'data' => $data]); ?> ``` ### 优点 - **灵活性**:可以处理各种格式的数据,而不仅仅是表单数据。 - **性能**:直接读取原始数据,避免了 PHP 自动解析表单数据的开销。 ### 注意事项 - **数据长度**:对于非常大的请求体,读取数据可能会消耗大量内存,需要注意数据长度。 - **安全性**:确保对读取到的数据进行适当的验证和消毒,以防止安全漏洞。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值