PHP $_POST Array Empty

Like this blog? Consider exploring one of our sponsored banner ads...

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;
 
}

About this entry