1

I'm trying to send json object from Android device to PHP to insert it to database, but server can't find it. What I did wrong? Thanks.

Script fails in isset check.

PHP Script:

    <?php

$json_array = json_decode($_POST['messages']) -> messages;

if(isset($json_array))
{
    //connect to database and do insertions.
} else
{
    echo "Not found array with messages in POST request\n";
}

Post request contains:

{"messages":[{"message":"Hello. Test from ukraine","id":1,"from_sender":"1111-111-1111","box":"2","type":"sms"}]}

And it's formed like this:

HttpClient httpClient = new DefaultHttpClient();

            try {
                HttpPost httpPost = new HttpPost(BASE_URL + "/josyko.php");
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("messages", request.toString()));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                result = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }

1 Answers1

2

You can use: http://php.net/manual/en/reserved.variables.httprawpostdata.php

$json_array = json_decode($HTTP_RAW_POST_DATA) -> messages;

Or a better solution:

file_get_contents('php://input'); // instead of $HTTP_RAW_POST_DATA
Robert
  • 33,429
  • 8
  • 90
  • 94
  • Do not use `$HTTP_RAW_POST_DATA`. [PHP Manual says](http://www.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data), “the preferred method for accessing the raw POST data is `php://input`”. – Denys Popov Dec 16 '13 at 17:46
  • On my local machine and webhosting it's working with $_POST, but on other hosting it's not working... I don't think that the problem is in $HTTP_RAW_POST_DATA... – user3080265 Dec 16 '13 at 17:50
  • http://stackoverflow.com/questions/8391302/json-post-request-parsing-in-php Answer found here. Thanks guys for trying to help – user3080265 Dec 16 '13 at 19:16