How to recover the body and header from a PHP POST transfer?

Asked

Viewed 1,383 times

2

To recover the content body of a transaction we received 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 I should certainly check the header.

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

1 answer

1


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

Code:

<?php

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

Exit:

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 

That is the function 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:

  • 1

    Hi Virgilio, if I understand then I should have it in my file entryPort.php (which is the gateway to all requests): $arrHeader = getallheaders() ... then I get my body back $bd=file_get_contents('php://input') and I can do the processing according to the company that sent me. Correct?

  • 1

    Ok I got it. In my case it didn’t work because I am using Nginx. But on the page you sent has a function for Nginx http://php.net/manual/en/function.getallheaders.php#84262

Browser other questions tagged

You are not signed in. Login or sign up in order to post.