HTTP Post not working with PHP in android - php

I learning android and trying to write some code to verify a username and password using a PHP script and a WAMP server. I keep getting undefined index errors from my PHP script. As far as I can ascertain that means my PHP script can't access the data from the URL. Here is the relevant code. Any help is appreciated.
//build url data to be sent to server
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PasswordCheck.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("Connection", "Error in http connection "+e.toString());
}
Here is my PHP script
<?php
mysql_connect("localhost", "root", "") or die("could not connect to mysql");
mysql_select_db("drop-in") or die("database not found");
$username = $_POST["username"];
$suppliedPassword = $_POST["password"];
$databasePassword = "";
$output = "false";
$query = mysql_query("SELECT Password FROM users WHERE Username = '$username'") or die("query failed");
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_assoc($query);
$databasePassword = $row['password'];
if($databasePassword == $suppliedPassword)
{
$output = "true";
}
}
print($output);
mysql_close();
?>
And here a picture of the server's reply
http://imgur.com/sQStI2D
EDIT: So I figured out that even though the PHP script is giving these errors the $username and $password variables contain the values my android app was attempting to pass along. However the presence of these errors is still messing with my code because the HTML for the error tables gets sent back to the android app in the response

To me it looks like your Android code isn't POSTing the "username" and "password" fields, that explains why the PHP script can't find them.
In your code, new ArrayList<NameValuePair>();, the length of the arrayList may be missing, by looking at this code sample: it looks like it should be new ArrayList<NameValuePair>(2);, you should try with that and see if resolves the issue.

Turns out it was a simple spelling error. I used a lower case 'p' in the word 'password' in my loop instead of an uppercase. Odd that it caused the error that it did.

You can try json_decode() function in PHP:
try to create A file on your server and put content of android request into simple text file you will get array output. in that file.
on your server in .php file write below code:
<?php
$data=file_put_content(collect.txt, $_POST);
// if you got to know object or array name from txt file use it.
$array=json_decode($data, true) // for array output.
print_r($array);
?>
and if you don't want to read from file you can directly use if you know array name, in json object
<?php
$array=json_decode($data) // remove true for use as an object output.
print_r($array);
?>
once you got your array assign values to new variables and do whatever you want with them. Update database or anything as per your requiremnet

Related

Inserting into a database via Android

I have the following problem:
I have set up a database using XAMPP and I've written 4 PHP-Scripts to insert and show the content of it. That works fine by now. The database has two columns body and address both of type text and it is there to write some sms data in it.
Now I want to insert from my Android app. To achieve this, I have written those few lines of code inside my app:
//the sms to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("body","testbody"));
nameValuePairs.add(new BasicNameValuePair("address", "testaddress"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/sms/addsms.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
Now the problem is - if the code above has no fault - how can I pass those BasicNameValuePairs into my PHP variables? My PHP script for this looks like the following:
<?php
//This is my problem: How can I write the values from inside
//my android application in to those variables here? :(
//Getting the JSON data sent by the android app
$json_body = $_REQUEST['body'];
//Converting it into a standard class object
$obj_body = json_decode($json_body, true);
//Getting the value associated to the 'body' property
$body = $obj_body->'body';
//Getting the JSON data sent by the android app
$json_address = $_REQUEST['address'];
//Converting it into a standard class object
$obj_address = json_decode($json_address, true);
//Getting the value associated to the 'body' property
$address = $obj_address->'address';
//Connecting to database
require_once('mysqli_connect.php');
//Defining the query for inserting
$query = "INSERT INTO sms (body, address) VALUES (?,?)";
//Preparing the statement to be executed
$stmt = mysqli_prepare($dbc, $query);
//Binding the parameters to the statement
mysqli_stmt_bind_param($stmt, "ss", $body, $address);
//Executing the statement
mysqli_stmt_execute($stmt);
?>
I can run the app on the emulator, but nothing happens, so I get no new entry in my database. Can someone explain to me, how I get this right in PHP? Or is there a fault in the android code?
rikojir

to read the single line echoed text from php web server using android

i just want to read the single line text that is echoed from the php web server .
but the my code reads the echoedd text along with the web pages source code i just want to remove the source code and get only the text is there any way to get text separately
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://www.rock.bugs3.com/check.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(newBasicNameValuePair("username",
et.getText().toString().trim()));
$Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(newBasicNameValuePair("password",
pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
i am new to both android as well as php .this is my php code which i have used
<?php
$hostname_localhost ="mysql.serversfree.com";
$database_localhost ="u154090_donor";
$username_localhost ="u154090_donor";
$password_localhost ="abcd";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
mysql_close($localhost);
?>`
You should choose a better transport protocol between your client and server.
HTML is meant to be rendered by a browser, and implies how the data is visually represented.
If you have programmed an endpoint in your PHP server that you call the get some data (only raw data without visual representation) your PHP script should output the data you need encoded in XML or JSON.
If you PHP definitively outputs HTML, you should use a XML parser in your android application to get the data you need inside the HTML.
The data sent back is controled by your php script check.php, not be the client. If there's too much data being sent back, the bug is in your php script or in your web server configuration.

Android PHP - Store Session to mySQL DB

I am a beginner in Android and I have the following code:
(On the PHP side, after the user logs into my Android App)
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM users WHERE c_name='$username' AND c_password='$password'") or die("Could not run query!");
$rows = mysql_num_rows($query);
if($rows == 0){
echo "No user was found";
}else{
$row = mysql_fetch_assoc($query);
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['c_name'];
echo "User Found";
}
In the file where I want to obtain the ID of the user whom was logged in I have:
session_start();
$r_name = $_POST['r_name'];
$r_address = $_POST['r_address'];
$r_phone = $_POST['r_phone'];
$r_username = $_POST['r_username'];
$req_id = $_SESSION['id'];
$req_username = $_SESSION['username'];
$query_add = "INSERT INTO data_collection VALUES ('','$r_name','$r_address','$r_phone','$r_username','$req_id')";
$query_exec = mysql_query($query_add) or die("Could not insert to db");
if($query_exec){
echo "Success";
}else
echo "Error in query";
And the Android side that posts the data to the 2nd php file:
public void onClick(View v) {
// TODO Auto-generated method stub
String s_res_name = res_name.getText().toString();
String s_res_address = res_address.getText().toString();
String s_res_phone = res_phone.getText().toString();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("r_name", s_res_name));//c_name is the value in PHP and in the mySQL db
nameValuePairs.add(new BasicNameValuePair("r_address", s_res_address));
nameValuePairs.add(new BasicNameValuePair("r_phone", s_res_phone));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/thesis/data_collection.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,responseHandler);
tv.setText(""+response);
if (response.equals("Success")){
Toast toast = Toast.makeText(getApplicationContext(), "Data Collection task successfully created", Toast.LENGTH_LONG);
toast.show();
finish();
}
}catch(Exception e){
Log.e("log.tag","Error in http connection"+e.toString());
}
}
});
How can I obtain the session ID in the second php file and store it in a new table?
This code runs well through the web, when I post the data through a form, but on the android side it doesn't...
Thank you for your help.
How can I obtain the session ID in the second php file and store it in a new table?
The session ID is part of the request. If you mean $_SESSION['id'] you need to call session_start() first or have session auto-start configured.
Do I have to do sth on the Android side? Thank you for your help.
Yes, you need to pass the real session ID (not that $_SESSION['id'] value), it's a cookie or a query-parameter commonly named PHPSESSID by default. See also session-name. If you don't pass that info with the request, PHP does not know which session this request should belong to.
For more info, please continue here: http://php.net/sessions
In my applications I do it this way:
I have PHP script, that do real login. This script return string as "HTML page". That page is erad within application, string is parsed and data from that string are used in application for login.
Example of return string:
nick|user_id|hashed_security_string
Now in nick you have user name, user_id is his ID from DB and hashed_security_string is something used for security purposes when you for example commit something from your app to DB, this string is send with data and controlled on server if user is really logged or if user exist.

How to recieve data from database back into android

I have created a webservice called "login.php" where I send the id and password information from android. The webservice successfully catches the id and password. I need to compare that id and password to the ones already present in the database and check whether they exist or not. If they do, I need to send back an "okay message" back to android so I can start a new intent. If the id and password do not exist, I want to display an error.
Below is my code.
Login.java
HttpPost httppost = new HttpPost("http://abc.com/webservice/Login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", et1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", et2.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
client.execute(httppost);
Log.d("valueeeeeeeeeeee", et6.getText().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
}
Login.php:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid = $_POST['userid'];
$pass = $_POST['pass'];
$db_select=mysql_select_db("my_db");
if(!$db_select){
die(mysql_error());
echo "error";
}
What query should I run here to check the database against the specific id and password it recieved and send back an "okay message" to the android app. Thanks
You can try something like this:
Java:
HttpPost httppost = new HttpPost("http://abc.com/webservice/Login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", et1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", et2.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//This piece of code should do the trick
HttpResponse response = client.execute(httppost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the reponse content
String content = EntityUtils.toString(respEntity);
}
Log.d("valueeeeeeeeeeee", et6.getText().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
}
PHP:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid = mysql_real_escape_string($_POST['userid']);
$pass = mysql_real_escape_string($_POST['pass']);
$db_select=mysql_select_db("my_db");
if(!$db_select){
die(mysql_error());
echo "error";
}
$query = "select count(1) as count_users from user_table where user_field = '".$userid."' and pass_field ='".$pass."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row['count_users']>0)
{
echo "Okey";
}
else
{
echo "Not found";
}
?>
PS: Please dont use the mysql_extension, go for mysqli or PDO instead.
I would recommend doing as you are. Initiate a HTTP post/get request to a PHP page which connects to the MySQL database using mysqli (mysql_query is deprecated). You can then form the result into a JSON response to be passed back and can be easily parsed in android to extract any wanted information. I would recommend these tutorials:
Connect android with PHP and MySql, JSON in android and PHP and MySQLi
I used these tutorials and managed to get what you are trying to do working without too much difficulty.
You can access the passed get variables sent from android using
$_GET['userid'] and $_GET['pass']
and a valid SQL query would be
$query = 'SELECT * FROM '%table_name%' WHERE uname ="'.$_GET['uname'].'" AND pass ="'.$_GET['pass'].'"';
You need to beware though as using unchecked input directly in SQL statements leaves you susceptible to SQL injection attacks and should be avoided if at all possible. For the purposes of investigating and experimenting on a private server you should be okay though. Be aware that that there is are a lot of security issues to consider before distributing software with server connectivity

error manipulating cursor result from mongodb while getting resuts to android client

I'm connecting to local web server from android client and getting results back from mongodb database.
<?php
$Earth_radius = 6378.137; //KM
$required_distance = 20; //KM
if(! isset($_POST['long']) || ! isset($_POST['lat']) )
{
echo 'NOT SET'; //exit();
}
$long = $_POST['lat'];
$lat = $_POST['long'];
// open connection to MongoDB server
$conn = new Mongo('localhost');
// access database
$db = $conn->matabatdb;
// access collection
$collection = $db->matabat;
$center=array($long,$lat);
$radius=$required_distance/$Earth_radius; //convert to radians
echo 'Im Ok here ';
$result = $collection->find(array("loc"=>array('$within'=>array('$centerSphere'=>array($center,$radius)))));
echo ' I can reach here';
var_dump($result->getNext());
echo 'I do not reach this line';
?>
Any manipulation to $result doesn't provide any feedback response to android client
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseText = EntityUtils.toString(entity);
Pattern pattern=Pattern.compile(".*?<body.*?>(.*?)</body>.*?",Pattern.DOTALL);
Matcher matcher=pattern.matcher(responseText);
if(matcher.find()) {
String userID = matcher.group(1).trim();
}
else
Log.i(TAG," POST RESPONSE "+ responseText);
}
else
Log.i(TAG," POST RESPONSE is NULL");
The strange thing is If I made an html file and posted data manually the code works in the browser but regarding to android, I do not receive any data back or more specifically any data after manipulating the cursor. any echo statements before that line is received in Android.
Any help ?
If the PHP script works from the browser. Then it's perhaps a data encoding problem.
Try using json_encode($result->getNext()) instead of var_dump($result->getNext()).

Categories