PHP $_POST Array Empty

Fellow PHP programmers, I encountered a most peculiar problem today that I must share. I had a situation where someone was sending me POST data but the PHP $_POST array was empty. I setup a debugging script to see the GET and POST arrays and sure enough everything was empty. I asked my friend Google and found a neat way to get the raw incoming message using PHP:

$data = file_get_contents('php://input');

That convinced me that they were in fact sending me what looked like POST data but for some reason the PHP $_POST array was still empty. Long story short, what I discovered and hopefully what will save someone out there some time, is that if the Content-Type is empty or not recognized in the HTTP message then the PHP $_POST array is empty. Not sure if this is a bug or is by design…

Anyway if the guy on the other end can’t figure out how to send a properly formatted HTTP message, you can force the Content-Type as a last resort using something like this above where you want to access the $_POST array:

if(empty($_SERVER['CONTENT_TYPE'])){   $type = "application/x-www-form-urlencoded";   $_SERVER['CONTENT_TYPE'] = $type;   }

 

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>',print_r($_POST, TRUE),'</pre><br /><br /><br />';
}

?>

<form method="post" action="">
    <input type="hidden" name="test1" value="one" />
    <input type="hidden" name="test2" value="two" />
    <input type="hidden" name="test3" value="three" />
    <input type="submit" value="Test Me" />
</form>

Source

http://www.bradino.com/php/empty-post-array/

http://stackoverflow.com/questions/1282909/php-post-array-empty-upon-form-submission

Leave a comment