Monday, April 27, 2015

How to create PHP web service with JSON respond? For Android, Iphone or Web Application.

There is a list at the official PHP website: http://www.php.net/manual/en/refs.webservice.php You can see that PHP can work with OAuth, SCA, SOAP, Yar and XML-RPC. But there is another way which is so simple to create a webservice. It is JSON.

I will show how to create a simple web service with JSON. Our service will get the parameters by using $_GET , therefore we will put the parameters to url. For instance http://mywebserviceurl.com?s=myparameter , so the service will answer depending on myparameter.

Lets look at service's index file:

index.php
   
<?php

include('connectdb.php');

$something = $_GET['s'];
$sqlcode = mysql_query("Select $something from mydb limit 5 ");

$jsonObj= array();
while($result=mysql_fetch_object($sqlcode))
{
  $jsonObj[] = $result;
}

$final_res =json_encode($jsonObj) ;
echo $final_res;
 
?>

connectdb.php
   
<?php
    $hostname="localhost";
    $username=""; //write your username
    $password=""; //write your password
    $db_name=""; //write your db name
    $con=mysql_connect($hostname,$username,$password);
    mysql_select_db($db_name,$con) or die ("Cannot connect the Database");
    mysql_query("SET NAMES 'utf8'",$con);

?>

Thats all. You will see the JSON results on the screen. You can validate the JSON results with the help of some sites. Json validator addresses:

http://jsoneditor.net/
http://jsonlint.com/

How to get results of a web service?

Your application will ask this webservice something, then the service will give response with a json result. Your application should get the results with a reader to read the webservice's output.

In PHP, you can do that with file_get_contents() function. Here is an example of my php application:

readwebservice.php
<?php
$jsonObj = file_get_contents('http://mywebserviceurl.com/?s=myparameter');
$final_res = json_decode($jsonObj, true) ;
var_dump( $final_res );
?>

In Android, you can use JSONParser.java which you can find the whole codes at the following topic below. You can simply use jsonParser.getJSONFromUrl() function to read the results. Here is example:

UserFunctions.java

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
  /**
  * function make webservice Request
  * @param myparameter
  * */
 public JSONObject loginUser(String myparameter){
  String webserviceURL = "http://mywebserviceurl.com/";
  JSONParser jsonParser = new JSONParser();
  // Building Parameters
  List params = new ArrayList();
  params.add(new BasicNameValuePair("s", myparameter));
  JSONObject json = jsonParser.getJSONFromUrl(webserviceURL, params);
  // return json
  // Log.e("JSON", json.toString());
  return json;
 }

Thats all for a simple webservice example. Lets look at an complex example now.


PHP LOGIN WEBSERVICE AND HOW TO USE IT IN ANDROID APP

If you want to create more complex webservices, I am gonna give you an example which is for "login" control. (If you want to look at my source files, you can download full "PHP Login Webservice" from https://sourceforge.net/p/phploginwebservice/)

Put the php web service codes into a directory which name is "android_login_api", so you can reach the web service via "http://mywebserviceurl.com/android_login_api/" url link. Also you should create another directory for other web service needs like "search" or "post" etc. By this way, you can seperate the service codes in a logical manner.

In web service with PHP:
index.php (Web service)
   
<?php

/**
 * File to handle all API requests
 * Accepts GET and POST
 *
 * Each request will be identified by TAG
 * Response will be JSON data

 /**
 * check for POST request
 */
if (isset($_POST['tag']) && $_POST['tag'] != '') {
 // get tag
 $tag = $_POST['tag'];

 // include db handler
 require_once 'DB_Functions.php';
 $db = new DB_Functions();

 // response Array
 $response = array("tag" => $tag, "success" => 0, "error" => 0);

 // check for tag type
 if ($tag == 'login') {
      // Request type is check Login
      $email = $_POST['email'];
      $password = $_POST['password'];

      // check for user
      $user = $db->getUserByEmailAndPassword($email, $password);
      if ($user != false) {
          // user found
          // echo json with success = 1
          $response["success"] = 1;
          $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 not found
          // echo json with error = 1
          $response["error"] = 1;
          $response["error_msg"] = "Incorrect email or password!";
          echo json_encode($response);
      }
 } else if ($tag == 'register') {
      // Request type is Register new user
      $name = $_POST['name'];
      $email = $_POST['email'];
      $password = $_POST['password'];

      // check if user is already existed
      if ($db->isUserExisted($email)) {
          // user is already existed - error response
          $response["error"] = 2;
          $response["error_msg"] = "User already existed";
          echo json_encode($response);
      } else {
          // store user
          $user = $db->storeUser($name, $email, $password);
          if ($user) {
               // user stored successfully
               $response["success"] = 1;
               $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"] = 1;
               $response["error_msg"] = "Error occured in Registartion";
               echo json_encode($response);
         }
      }
 } else {
  echo "Invalid Request";
 }
} else {
 echo "Access Denied";
}
?>

DB_Functions.php (Web service)

   
<?php
class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->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
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {
        $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
        // check for result
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $salt = $result['salt'];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            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;
    }
}

?>

DB_Connect.php (Web service)

   
<?php
class DB_Connect {

    // constructor
    function __construct() {
        
    }

    // destructor
    function __destruct() {
        // $this->close();
    }

    // Connecting to database
    public function connect() {
        /**
         * Database config variables
         */
         define("DB_HOST", "localhost");
         define("DB_USER", "my_db_user");
         define("DB_PASSWORD", "my_db_pass");
         define("DB_DATABASE", "my_db_name");

        // connecting to mysql
        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        // selecting database
        mysql_select_db(DB_DATABASE);

        // return database handler
        return $con;
    }

    // Closing database connection
    public function close() {
        mysql_close();
    }

}
?>

This is all for web service. Now you can go to Android app source codes. In Android:

JSONParser.java (Android)

   
package com.myapp.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

 static InputStream is = null;
 static JSONObject jObj = null;
 static String json = "";

 // constructor
 public JSONParser() {

 }

 public JSONObject getJSONFromUrl(String url, List params) {

  // Making HTTP request
  try {
   // defaultHttpClient
   DefaultHttpClient httpClient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(url);
   httpPost.setEntity(new UrlEncodedFormEntity(params));

   HttpResponse httpResponse = httpClient.execute(httpPost);
   HttpEntity httpEntity = httpResponse.getEntity();
   is = httpEntity.getContent();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

  try {
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     is, "iso-8859-1"), 8);
   StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
   is.close();
   json = sb.toString();
   Log.e("JSON", json);
  } catch (Exception e) {
   Log.e("Buffer Error", "Error converting result " + e.toString());
  }

  // try parse the string to a JSON object
  try {
   jObj = new JSONObject(json);  
  } catch (JSONException e) {
   Log.e("JSON Parser", "Error parsing data " + e.toString());
  }

  // return JSON String
  return jObj;

 }
}


UserFunctions.java (Android)

package com.myapp.library;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;

public class UserFunctions {
 
 private JSONParser jsonParser;
 
 private static String loginURL = "http://mywebserviceurl.com/android_login_api/";
 private static String registerURL = "http://mywebserviceurl.com/android_login_api/";
 
 private static String login_tag = "login";
 private static String register_tag = "register";
 
 // constructor
 public UserFunctions(){
  jsonParser = new JSONParser();
 }
 
 /**
  * function make Login Request
  * @param email
  * @param password
  * */
 public JSONObject loginUser(String email, String password){
  // Building Parameters
  List params = new ArrayList();
  params.add(new BasicNameValuePair("tag", login_tag));
  params.add(new BasicNameValuePair("email", email));
  params.add(new BasicNameValuePair("password", password));
  JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
  // return json
  // Log.e("JSON", json.toString());
  return json;
 }
 
 /**
  * function make Login Request
  * @param name
  * @param email
  * @param password
  * */
 public JSONObject registerUser(String name, String email, String password){
  // Building Parameters
  List params = new ArrayList();
  params.add(new BasicNameValuePair("tag", register_tag));
  params.add(new BasicNameValuePair("name", name));
  params.add(new BasicNameValuePair("email", email));
  params.add(new BasicNameValuePair("password", password));
  
  // getting JSON Object
  JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
  // return json
  return json;
 }
 
 /**
  * Function get Login status
  * */
 public boolean isUserLoggedIn(Context context){
  DatabaseHandler db = new DatabaseHandler(context);
  int count = db.getRowCount();
  if(count > 0){
   // user logged in
   return true;
  }
  return false;
 }
 
 /**
  * Function to logout user
  * Reset Database
  * */
 public boolean logoutUser(Context context){
  DatabaseHandler db = new DatabaseHandler(context);
  db.resetTables();
  return true;
 }
 
}

In your application, you can use this UserFunctions.java like that:

import com.myapp.library.UserFunctions;

Lets say our response JSON of webservice will be like that:


{ "success": 1,
  "user": {
     "name":"Seval",
     "email":"hello@hotmail.com"
   }
}

You can call parse the results in a function, for example "loginUser":

JSONObject json = userFunction.loginUser(email, password);

// check for login response
String res = json.getString("success");
if(Integer.parseInt(res) == 1){
   JSONObject json_user = json.getJSONObject("user");
   String name = json_user.getString("name");
   String email = json_user.getString("email");
}

No comments:

Post a Comment