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.
Related
i know this could look like a really simple question to somebody, but i'm quite new to PHP. By the way..
I want a user to login on an android app, and this login request has to be handled by a PHP page, i wrote this for the android part:
try{
String url = "https://MYWEBSITE:80/login?username=" + mEmail + "&password=" + mPassword;
HttpParams parameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(parameters, 1000 * 60 * 2);
HttpConnectionParams.setSoTimeout(parameters, 0);
HttpClient httpClient = new DefaultHttpClient(parameters);
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(url);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection
// manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
}
}catch (Exception e) {
e.printStackTrace();
}
but i have no idea what to write in the PHP file, can anyone help me?
Firstly, you have to create a table lets say "users"
USER TABLE
==========
ID (Primary) USERNAME (VARCHAR) PASSWORD (VARCHAR)
============================================================================
1 webzar abc123
2 someone 222222
Then create a file login.php
login.php
=========
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("YOUR DB NAME") or die(mysql_error());
$username = $_GET['username']; // GET USERNAME
$password= $_GET['password']; // GET PASSWORD
if($username != '' and $password != '')
{
$sql = mysql_query("SELECT * FROM users WHERE username = '$username ' and password = '$password'") or die(mysql_error());
if(mysql_num_rows($sql) > 0) // CHECK FOR USER CREDENTIALS
{
// IF INFO IS CORRECT
$fetch = mysql_fetch_array($sql);
echo 'Logged In';
}
else
{
echo 'Cannot Login!';
}
}
?>
Well, it depends on what the rest of your backend looks like.
For example, if you have a MySQL database of your users, you need to simply check if the username and password match the ones stored in you database and return a flag that says "valid username and password, authentication succeeded".
Maybe you could give more information about how you are authenticating the user on your website and what kind of database do you use to store the information about the users.
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
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.
I havnt been able to find a guide on how to submit data to a database from android through php.
say for instance i have the following site:
function insert($var1) {
// mysql inserting a new row
$result = mysql_query("INSERT INTO report (name) VALUES ('$var1')");
// check if row inserted or not
if ($result) {
// successfully inserted into database;
$msg = "Message received.";
} else {
$msg = "Not received.";
}
return ($msg);
}
if (isset($_POST['name'])) {
$name = $_POST['name']);
insert($name);
} else {
echo "No input.";
}
How would i call this from my Android project?
You can refer to this tutorial but you do need a web-server for it.
Request mechanism Android App ----> webserver ------> database (mysql)
Respond mechanism Android App <---- webserver <------ database (mysql)
Android App will use JSON or other to get the data and display it
PHP Code
<?php
$con=mysql_connect("host","username");
if(!$con)
{
die("Could Not Connect".mysql_error());
}
$db="CREATE DATABASE login";
mysql_query($db,$con);
mysql_select_db("login",$con);
$tab="CREATE TABLE info(FirstName varchar(20),LastName varchar(20))";
mysql_query($tab,$con);
$user_fname=$_POST['fn'];
$user_lname=$_POST['ln'];
$row= mysql_query("INSERT INTO info (FirstName,LastName) VALUES('$user_fname', '$user_lname')");
if ($row) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo $row;
}
mysql_close($con);
?>
Sending the Data (Android)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1:4001/file.php");
List<NameValuePair> pair=new ArrayList<NameValuePair>(2);
pair.add(new BasicNameValuePair("fn",fname));
pair.add(new BasicNameValuePair("ln",lname));
httppost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = httpclient.execute(httppost);
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