I am using a cross domain and uses php server to get user info when logging in. In my running website I use php code and when the user login I added this code
session_start();
Then just declare the user info when successfully logged in like:
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['user_email'];
$_SESSION['user_name'] = $user['user_name'];
And then I use that session $user['user_id'];
in every user requests.
How to implement a session when the user logged on Hybrid app? Is it the same on how my running website works? Do I just need to add session code on the ajax request? Any idea?
To do this you need a host server that will authenticate and talk to your devices. Common protocols would be the use of cURL
and JSON
response:
REMOTE DEVICE
1) Your device, I will use another server because it's easy, will start a connection using cURL:
function cURL($variables = false)
{
$url = "http://www.example.com/";
$query = (!empty($variables))? '?'.http_build_query($variables) : '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.$query);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(!empty($response))
$data = json_decode($response,true);
curl_close($ch);
return $data;
}
$login = cURL(array(
'service'=>'login',
'apikey'=>123123,
'username'=>'whatever',
'password'=>'whatever')
);
print_r($login);
API HOST SERVER
2) Your server then will be listening for services. I am using $_GET
but $_POST
is better:
if(!empty($_GET['service'])) {
switch($_GET['service']) {
case('login'):
logInUser($_GET);
}
}
The logInUser()
function would just do the normal login function except that it would set timestamp
, token
, apikey
, and username
in the database and return that via json on success:
//...authentication code here...//
if($valid) {
// However you want to make a token
$token = md5($usename.mt_rand(1000000,9999999).time());
// Do code here to save the username, token, apikey, timestamp into database
// This will then echo back the token on success to the device
die(json_encode(array('token'=>$token,'success'=>true)));
}
else {
die(json_encode(array('token'=>'','success'=>'bad username/password')));
}
After this point, the device calls back to the host with the token in the query string as well as the apikey. It would also include a service and any variables that the service requires to send data back to the device. Every hit to the server triggers the server to look for an apikey, then service, then if service is not login
, would require the token. It would query the database and check that all those things in the database are valid. If the token exists and the timestamp is recent enough (you can set the expiration time on that) then service runs. After service runs (or before complete), the timestamp
value for the token is updated to current time.