Kraken
Kraken

Reputation: 24233

How to extract POST parameters in php

From android app, I am calling my php script.

HttpPost httppost = new HttpPost("http://www.smth.net/some.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pa", "555"));
nameValuePairs.add(new BasicNameValuePair("pb", "550"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
}

How do I get the value of "pa" and "pb" in my php script.

I did $_POST['pa'] and urldecode($_POST['pa']) but both of these give me empty string.

Upvotes: 0

Views: 1400

Answers (3)

thomas
thomas

Reputation: 915

You can check the content of $_POST array by using extract() function, The function reads all key-value pairs and creates variables with the key as name and the value as variable content. See the example below:

<form method="post" aciton="extract.php">
  <input type="text" name="foo" />
  <input type="submit" />
</form>
<pre>
<?php
  function dump_extracted_post() {
    extract($_POST);
    var_dump(get_defined_vars());
  }
  dump_extracted_post();
?>
</pre>

Read more in How to extract $_GET / $_POST parameters in PHP

Upvotes: 0

Mark Ormesher
Mark Ormesher

Reputation: 2408

You can use print_r($_POST) to debug what is being sent.

If it helps, this is how I send info from Android using POST:

JSONObject requestBody = new JSONObject();
requestBody.put("pa", "550");
requestBody.put("pb", "550");

HttpPost requestBase = new HttpPost("url");
StringEntity stringEntity = new StringEntity(requestBody.toString());
stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
requestBase.setEntity(stringEntity);

HttpResponse response = httpclient.execute(requestBase);

I'm working from memory here though - there are a couple of try/catches you'll need to insert.

Using a JSONObject might be unnecessary, but I found it gave me better flexibility and reliability.

Upvotes: 1

user2684182
user2684182

Reputation:

You want to use the $_POST environment variable. So, in your code, you can use $_POST["pa"] and $_POST["pb"].

If this doesn't work, try using var_dump to check the contents of $_POST (var_dump($_POST)). If it is empty, then it is a problem with your android code.

Upvotes: 1

Related Questions