Using PHP Sessions with My Android Login Application

I am trying to make a login script for my Android application, the script will send my email address and password to the PHP server, verify the login and then create a PHP session so that the user remains logged in. This is my code,

HttpPost httppost = new HttpPost("http://server.com/login.php");
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();

public String login() {

    String userID = "";

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("email", "e@e.com"));
        nameValuePairs.add(new BasicNameValuePair("password", "admin"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        userID = EntityUtils.toString(response.getEntity());
        //Log.v("Login response", "" + userID);



    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return userID;
} 

This script successfully sends data to my server, and my PHP successfully logs the user. I posted "HttpClient httpclient = new DefaultHttpClient ();" outside my main login method. This helped save the session until I called another class and then reset the session again. Therefore, I am wondering how I can change the code so that the "httpclient" is somehow saved, so I can maintain a session and stay on my server. Thank!

+5
2

Android Http cookie

cookie cookie .

+3

- php- -, session_id, login.Let android . post sess_id = id

<?php
if(isset($_POST['sess_id']))
{
session_id($_POST['sess_id']); //starts session with given session id
session_start();
$_SESSION['count']++;
}
else {
session_start(); //starts a new session
$_SESSION['count']=0;
}
echo session_id();
?>
+2

All Articles