How To Register and Login Using PHP Webservices in Android App.
Hello, friends this post is about How to make a register and login page by using php webservices in android .
In this tutorial we will create a simple App where user can register and then the user can login. So lets begin creating an app for Android Login and Registration with PHP Webservices.
In this tutorial we will create a simple App where user can register and then the user can login. So lets begin creating an app for Android Login and Registration with PHP Webservices.
- So, I am using a Hostinger server instead of local server for calling a PHP webservices.
1. Create a Database For Application:-
- Go to PHPMyAdmin and create the following table. (I am using Hostinger’s free hosting).
- For Creating a database use following code:-
Create
database
android /** Creating
Database
**/
use android /** Selecting
Database
**/
create
table
users(
id
int
(11)
primary
key
auto_increment,
unique_id
varchar
(23)
not
null
unique
,
name
varchar
(50)
not
null
,
email
varchar
(100)
not
null
unique
,
encrypted_password
varchar
(80)
not
null
,
salt
varchar
(10)
not
null
,
created_at datetime,
updated_at datetime
null
); /** Creating Users
Table
**/
2. Server Side PHP Code For Application:-
- Go to your server’s directory and create a folder for this project. (I created Android_User)
- Put all the PHP file in the Android_user Created Directory.
(i) Config.php
<?php
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "root");
define("DB_DATABASE", "android_api");
?>
(ii) DB_Connect.php
<?php
class DB_Connect {
private $conn;
// Connecting to database
public function connect() {
require_once 'Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
}
?>
(iii) DB_Functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return NULL;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
(iv) register.php
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (name, email or password) is missing!";
echo json_encode($response);
}
?>
(v.) login.php
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password']))
{
// receiving the post params
$email = $_POST['email'];
$password = $_POST['password'];
// get the user by email and password
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters email or password is missing!";
echo json_encode($response);
}
?>
3. Json Responses:-
There are different types of json responses from server for registration :-
3.1. Registration
Parameters: name,email,password
(i ) Registration Success Response:-
{
"error": false,
"uid": "55fa7220a2c187.50984590",
"user":
{
"name": "Varun Kumar",
"email": "simplifiedandroidcoding@blogspot.info",
"created_at": "2015-09-17 13:26:16",
"updated_at": null
}
}
}
(ii) Registration Error in Storing a Data in a Database:-
{
"error": 1,
"error_msg": "Unknown error occurred in registration!"
}
(iii) Registration Error- If User already registered:-
{
"success": 0,
"error": 2,
"error_msg": "User already existed with varun@simplifiedandroidcoding.info"
}
3.2 Login
Parameters:- email, password
(i) Login Response - Success
"error": false,
"uid": "5550984590",
"user": {
"name": "Varun Kumar",
"email": "saurabh@android.com",
"created_at": "2015-09-17 13:26:16",
"updated_at": null
}
}
(ii) Login Error- Incorrect Username, Password
{
"tag": "login",
"success": 0,
"error": 1,
"error_msg": "Login credentials are incorrect. Please try again!"
}
(4.) Now Come to on android code:-
- First you have to create a project in android studio.
- Download httpclient-4.3.5.jar file from here-http://www.java2s.com/Code/Jar/h/Downloadhttpclient423jar.html
- Download httpcore-4.3.2.jar file from here-http://grepcode.com/snapshot/repo1.maven.org/maven2/org.apache.httpcomponents/httpcore/4.3.2
- Download apache-mime4j-core-0.7.2 file from here-https://james.apache.org/mime4j/start/download.html
- Put this all above downloaded .jar file and put in a libs folder.
- After that compile this library's in to build.gradel file.
# The Code Below :-
dependencies
{
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:design:23.1.1'
compile 'com.squareup.okhttp:okhttp:2.0.0'
compile files('libs/httpclient-4.3.5.jar')
compile files('libs/apache-mime4j-core-0.7.2.jar')
compile files('libs/httpcore-4.3.2.jar')
compile 'com.android.support:multidex:1.0.0'
}
(4.) Android UI xml file.
(i) activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#607D8B"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp" >
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#00BCD4"
android:hint="Name"
android:padding="10dp"
android:singleLine="true"
android:inputType="textCapWords"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white" />
<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#00BCD4"
android:hint="Email"
android:inputType="textEmailAddress"
android:padding="10dp"
android:singleLine="true"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white" />
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#00BCD4"
android:hint="Password"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white" />
<Button
android:id="@+id/btnRegister"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#00BCD4"
android:text="Register"
android:textColor="@android:color/white" />
<Button
android:id="@+id/btnsignin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#00BCD4"
android:text="Login"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
(ii) MainActivity.class
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { EditText email,name,password; Button btnRegister,btnsignin; HttpPost httppost; HttpClient httpclient; List<NameValuePair> nameValuePairs; ProgressDialog dialog = null; JSONObject object1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name=(EditText)findViewById(R.id.name); email=(EditText)findViewById(R.id.email); password=(EditText)findViewById(R.id.password); btnRegister=(Button)findViewById(R.id.btnRegister); btnsignin=(Button)findViewById(R.id.btnsignin); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog = ProgressDialog.show(MainActivity.this, "", "Registering User...", true); new Thread(new Runnable() { public void run() { register(); } }).start(); } }); btnsignin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this,Mapage.class); startActivity(intent); } }); } void register() { try{ httpclient=new DefaultHttpClient();
//Here enter your own url httppost= new HttpPost("http://url/php_register/register.php"); nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("name",name.getText().toString())); nameValuePairs.add(new BasicNameValuePair("email",email.getText().toString())); nameValuePairs.add(new BasicNameValuePair("password",password.getText().toString())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response1 = httpclient.execute(httppost); String jsonResult = inputStreamToString(response1.getEntity().getContent()).toString(); object1 = new JSONObject(jsonResult); String error=object1.getString("error"); final String error_msg=object1.getString("error_msg"); runOnUiThread(new Runnable()
{
public void run()
{ dialog.dismiss(); Toast.makeText(MainActivity.this,"Register Successfully:-"+error_msg,Toast.LENGTH_LONG).show(); } }); }catch(Exception e){ dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } private StringBuilder inputStreamToString(InputStream is) { String rLine = ""; StringBuilder answer = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((rLine = rd.readLine()) != null) { answer.append(rLine); } } catch (IOException e) { e.printStackTrace(); } return answer; } public void onBackPressed() { this.finish(); } }
(iii) activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#607D8B"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp" >
<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#00BCD4"
android:hint="Enter your email"
android:inputType="textEmailAddress"
android:padding="10dp"
android:singleLine="true"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white" />
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#00BCD4"
android:hint="Enter your password"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="@android:color/white"
android:textColorHint="@android:color/white" />
<Button
android:id="@+id/btnlogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#00BCD4"
android:text="Login"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
(iv) Login.xml
import java.io.BufferedReader;import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Login extends Activity { EditText email,password; Button btnlogin; HttpPost httppost; HttpClient httpclient; List<NameValuePair> nameValuePairs; ProgressDialog dialog = null; JSONObject object1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_Login); email=(EditText)findViewById(R.id.email); password=(EditText)findViewById(R.id.password); btnlogin=(Button)findViewById(R.id.btnlogin); btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog = ProgressDialog.show(Login.this, "", "Validating user...", true); new Thread(new Runnable() { public void run() { login(); } }).start(); } }); } void login(){ try{ httpclient=new DefaultHttpClient(); httppost= new HttpPost("http://e-programming.com/php_register/login.php"); nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("email",email.getText().toString())); nameValuePairs.add(new BasicNameValuePair("password",password.getText().toString())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response1 = httpclient.execute(httppost); String jsonResult = inputStreamToString(response1.getEntity().getContent()).toString(); object1 = new JSONObject(jsonResult); String error=object1.getString("error"); final String error_msg=object1.getString("error_msg"); runOnUiThread(new Runnable() { public void run() { dialog.dismiss(); Toast.makeText(Login.this,"Login Successfully:-"+error_msg,Toast.LENGTH_LONG).show(); } }); }catch(Exception e){ dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } private StringBuilder inputStreamToString(InputStream is) { String rLine = ""; StringBuilder answer = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((rLine = rd.readLine()) != null) { answer.append(rLine); } } catch (IOException e) { e.printStackTrace(); } return answer; } public void onBackPressed() { Intent intent=new Intent(Login.this,MainActivity.class); startActivity(intent); } }(5.) ScreenShots
(i)Register.
(ii)Login.
0 comments:
Post a Comment