How to retrieve the body and header of a POST transaction in PHP?

2

To retrieve the contents body of a transaction that we receive via POST we use this function file_get_contents('php://input') . But there are several companies that can send a post request to our service and I need to know who is who, so surely I should check the header .

What function should I use to retrieve body and header at the same time?

    
asked by anonymous 04.05.2017 / 21:21

1 answer

1

There is no function that at the same time makes both have to use the function getallheaders () ( which is a nickname for apache_request_headers () and also file_get_contents('php://input') and redeem header and body respectively:

Code:

<?php

    foreach (getallheaders() as $header => $value) {
        echo "$header: $value <br />\n";
    }

Output:

Content-Type: 
Content-Length: 0 
Upgrade-Insecure-Requests: 1 
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
            AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36 
Host: localhost 
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 
Accept-Encoding: gzip, deflate, sdch, br 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 
Connection: keep-alive 
Cache-Control: max-age=0 

In other words, getallheaders () returns a array as follows:

array(10) {
  ["Content-Type"]=>
  string(0) ""
  ["Content-Length"]=>
  string(1) "0"
  ["Upgrade-Insecure-Requests"]=>
  string(1) "1"
  ["User-Agent"]=>
  string(114) "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
              AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36"
  ["Host"]=>
  string(9) "localhost"
  ["Accept-Language"]=>
  string(35) "pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4"
  ["Accept-Encoding"]=>
  string(23) "gzip, deflate, sdch, br"
  ["Accept"]=>
  string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
  ["Connection"]=>
  string(10) "keep-alive"
  ["Cache-Control"]=>
  string(9) "max-age=0"
}

References:

04.05.2017 / 21:59