title: Securing php api to use in android application
body: <p>I am newbie to android development. I am using <code>android studio</code> for developing an application. Things i have done </p>
  
  <ol>
  <li>Created a <code>DB</code> with two tables in it in <code>MySQL</code>.</li>
  <li>Created two separate <code>api's</code> for both <code>GET</code> and <code>POST</code> methods.</li>
  <li>Successfully accessed both <code>api's</code></li>
  </ol>
  
  <p>What i have achieved for now </p>
  
  <ol>
  <li>Able to <code>GET</code> data form the GET <code>api</code>.</li>
  <li>Able to <code>POST</code> data using the POST <code>api</code></li>
  </ol>
  
  <p>What i have to do now </p>
  
  <p>I want my api to publish online, i.e. I want to deploy my services into a server and access them. At this point i am able to deploy the services on the server and accessed them. </p>
  
  <p>Now i want my services(<code>api's</code>) to be secured. For that i have searched many articles and found two ways. </p>
  
  <ol>
  <li>Use <code>yii</code> framework. Someone told me to use it because it automatically secured the <code>api's</code>. But i don't know for sure whether it do or not.</li>
  <li>Manually secure the <code>api's</code></li>
  </ol>
  
  <p>As for point <code>1</code> the framework will be helpful but it's new to me and it will take time to coop with it as i am already created the web services. </p>
  
  <p>For point <code>2</code> i got some information </p>
  
  <ol>
  <li><a href="https://stackoverflow.com/a/4904894/6854117">using HMAC_SHA1</a></li>
  <li><a href="http://www.hand-interactive.com/resources/detect-mobile-php.htm" rel="noreferrer">DETECTING MOBILE DEVICES USING PHP</a></li>
  </ol>
  
  <p>Both links seems to be good but link <code>1</code> doesn't gives me much info on that.</p>
  
  <p>Obviously i want to secure my both <code>api's</code> </p>
  
  <p><strong>Now the code part</strong></p>
  
  <p><strong>GET_DATA.php</strong></p>
  
  <pre><code>require_once ('config.php');
  
  $sql = "SELECT * FROM users";
  
  
  $r = mysqli_query($con,$sql);
  
  $result = array();
  
  while($row = mysqli_fetch_array($r)){
  array_push($result,array(
      'Id'=&gt;$row['Id'],
      'Name'=&gt;$row['Name']
  ));}
  </code></pre>
  
  <p>echo json_encode(array('users'=>$result));</p>
  
  <p><strong>POST_DATA.php</strong></p>
  
  <pre><code>require_once ('config.php');
  
  $return_arr = array();
  
  $UserId=($_POST['UserId']);
  $Latitude=($_POST['Latitude']);
  $Longitude=($_POST['Longitude']);
  $DateTime=($_POST['DateTime']);
  
  
  $user_register_sql1 = "INSERT INTO `activity`(`Id`,`UserId`, `Latitude`,`Longitude`,`DateTime`) values (NULL,'".$UserId."','".$Latitude."','".$Longitude."','".$DateTime."')";
  mysqli_query ($con,$user_register_sql1);
  $row_array['errorcode1'] = 1;
  </code></pre>
  
  <p>I have a <code>user class</code> from which i am getting <code>username</code> and <code>ID</code></p>
  
  <p><strong>JSONfunctions.java</strong></p>
  
  <p>This class is responsible for getting data from the <code>api</code></p>
  
  <pre><code> public static JSONObject getJSONfromURL(String url)
  {
  
      String json = "";
      JSONObject jsonObject = null;
      try
      {
          HttpClient httpClientt = new DefaultHttpClient();
          HttpGet httpGet = new HttpGet(url);
          HttpResponse httpResponse = httpClientt.execute(httpGet);
          BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
          StringBuffer sb = new StringBuffer();
          String line = "";
          while ((line = br.readLine()) != null) {
              sb.append(line);
          }
  
          json = sb.toString();
      } catch (ClientProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
  
      try
      {
          jsonObject = new JSONObject(json);
      } catch (JSONException e) {
          e.printStackTrace();
      }
  
      return jsonObject;
  }
  </code></pre>
  
  <p><strong>PutUtility.Java</strong></p>
  
  <p>This class is responsible for <code>POST</code> method</p>
  
  <pre><code>public void setParam(String key, String value) {
      params.put(key, value);
  }
  
  public String postData(String Url) {
  
      StringBuilder sb = new StringBuilder();
      for (String key : params.keySet()) {
          String value = null;
          value = params.get(key);
  
  
          if (sb.length() &gt; 0) {
              sb.append("&amp;");
          }
          sb.append(key + "=" + value);
      }
  
      try {
          // Defined URL  where to send data
  
          URL url = new URL(Url);
  
          URLConnection conn = null;
          conn = url.openConnection();
  
          // Send POST data request
          httpConnection = (HttpURLConnection) conn;
          httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          httpConnection.setRequestMethod("POST");
          httpConnection.setDoInput(true);
          httpConnection.setDoOutput(true);
          OutputStreamWriter wr = null;
  
          wr = new OutputStreamWriter(conn.getOutputStream());
          wr.write(sb.toString());
          wr.flush();
  
          BufferedReader in = new BufferedReader(
                  new InputStreamReader(httpConnection.getInputStream()));
          String inputLine;
          response = new StringBuffer();
  
          while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
          }
          in.close();
  
      } catch (MalformedURLException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }finally {
          try {
              reader.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  
  
      return response.toString();
  }
  </code></pre>
  
  <p><strong>MainActivity.java</strong></p>
  
  <pre><code> protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
      _latitude = (TextView)findViewById(R.id.latitude);
      _longitude = (TextView)findViewById(R.id.longitude);
      btn_get_coordinates = (Button)findViewById(R.id.button);
      btn_save_data = (Button)findViewById(R.id.btn_save);   
  
  
      btn_save_data.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
  
              if(UserId.toString()== "" || Latitude.toString() == "" || Longitude.toString() == "" || DateTime.toString() == "")
              {
                  Toast.makeText(getApplicationContext(), "Data Not Saved !!!! Please select appropriate data to save", Toast.LENGTH_SHORT).show();
              }
  
  
              new ServiceLogin().execute(UserId, Latitude, Longitude, DateTime);
  
          }
      });
  
      // Download JSON file AsyncTask
      new DownloadJSON().execute();
  }
      // Download JSON file AsyncTask
  private class DownloadJSON extends AsyncTask&lt;Void, Void, Void&gt;
  {
  
     @Override
      protected void onPreExecute() {
          super.onPreExecute();
          progressDialog = new ProgressDialog(MainActivity.this);
          progressDialog.setMessage("Fetching Users....!");
          progressDialog.setCancelable(false);
          progressDialog.show();
  
      }
  
      @Override
      protected Void doInBackground(Void... params) {
  
          // Locate the Users Class
          users = new ArrayList&lt;Users&gt;();
  
          // Create an array to populate the spinner
          userList = new ArrayList&lt;String&gt;();
          // http://10.0.2.2:8000/MobileApp/index.php
          //http://10.0.2.2:8000/app/web/users/
          //http://192.168.100.8:8000/app/web/users/
          // JSON file URL address
          jsonObject = JSONfunctions.getJSONfromURL("http://192.168.100.9:8000/MobileApp/GET_DATA.php");
  
          try
          {
              JSONObject jobj = new JSONObject(jsonObject.toString());
              // Locate the NodeList name
              jsonArray = jobj.getJSONArray("users");
  
              for(int i=0; i&lt;jsonArray.length(); i++)
              {
                  jsonObject = jsonArray.getJSONObject(i);
  
                  Users user = new Users();
  
                  user.setId(jsonObject.optString("Id"));
                  user.setName(jsonObject.optString("Name"));
                  users.add(user);
  
                  userList.add(jsonObject.optString("Name"));
  
              }
          } catch (JSONException e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
  
  
          return null;
      }
  
      @Override
      protected void onPostExecute(Void args)
      {
          // Locate the spinner in activity_main.xml
          Spinner spinner = (Spinner)findViewById(R.id.spinner);
  
          // Spinner adapter
          spinner.setAdapter(new ArrayAdapter&lt;String&gt;(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));
  
          // Spinner on item click listener
  
          spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  
  
              @Override
              public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) {
  
                  textViewResult = (TextView)findViewById(R.id.textView);
  
                  // Set the text followed by the position
  
                  textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());
                  UserId = String.valueOf(users.get(position).getId());
                  progressDialog.dismiss();
                  _latitude.setText("");
                  _longitude.setText("");
                  Latitude = null;
                  Longitude= null;
  
              }
  
              @Override
              public void onNothingSelected(AdapterView&lt;?&gt; parent) {
                  textViewResult.setText("");
              }
          });
      }
  
  
  }
  </code></pre>
  
  <p>As i am newbie, so i don't know what to do in <code>php</code> script and what to do in my android code :(. It would be very helpful if anyone can guide me or give me a tutorial that i follow. </p>
  
  <p>Any help would be highly appreciated.</p>