Search code examples
phphttphttpwebrequest

$_POST variable empty in php


I saw a few posts here that have the same problem but none of them are a simple as mine and hence the post.

I am new to php and I see that the $_POST and $_REQUEST variable are both empty. I can get the headers using the apache_request_headers() and am able to see the headers properly. It's just the $_POST variable is empty.

My client is an Android app and is generating the post message properly. I used tcpdump to test it. Also apache logs show that the intended PHP is invoked. I use Apache 2.2.14 and PHP 5.2.12 the standard installation, nothing special.

Can anyone think of any reason why the $_POST variable is empty?

Also I am not using a class in my code. Its just plain code which calls functions from other classes as needed. I mention this because I saw another post that suggests to use $this->input->post() but that is not possible in my case.

EDIT: Found the problem thanks to Sean below. The "Content-Type" was not set properly and that caused the actual values not reaching the php code. Oddly enough the headers of the empty request are what I set them to. Why would the data be stripped?


Solution

  • Make sure that your Android client is sending the correct content type on POST. It should be set to application/x-www-form-urlencoded.

            url = new URL("your URL");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");