I am doing a hybrid app with Phonegap (using only HTML5, CSS and JS - jQuery and JQuery Mobile). For this, I have the application itself, which can not use PHP, and a server apart that takes care of things like login. There is also a database.
Basically, I use Ajax requests that are received by the server, returning the database values by JSON so that they are displayed on the page. Login also works similarly: the values entered in the inputs are sent to a PHP file on the server, which validates the user and the password and gives a response to the application.
function Authenticate(username, password) {
$.ajax({
type: 'post',
dataType: 'json',
url: 'http://localhost/app/login.php',
data: { action: 'auth', username: username, password: password },
success: function(data){
if(data.result == 'true') {
$(':mobile-pagecontainer').pagecontainer('change', '#events', {
transition: 'none',
changeHash: false,
reverse: false,
showLoadMsg: true
});
}
else {
$('#login-error').show();
$('#login-error').html('Usuário ou senha incorreta.');
$('#login-password').addClass('error');
}
},
error: function() {
alert('Erro Ajax');
}
});
}
And the PHP file that receives the data:
case 'auth':
$sql = "SELECT * FROM users WHERE username = ? AND password = ?";
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
$res = 'true';
}
else {
$res = 'false';
}
echo json_encode(array("result" => $res));
break;
As a very basic system, the user is redirected to the #events page (how JQuery Mobile works) if the server response is "true" when searching for an entry in the database with that user and that particular password.
Browsing about sessions, I saw that they always have to be created and managed on the server side, but I could not think of any way to do that in my case.
How can I create a session for the user on the server side when he logs in and access the session variables in the Javascript application, for example, redirecting him directly from the #login page to the #events page, if already is there a valid session, or, likewise, redirect it from the #events page to the #login page, if there is no valid session and the user is not logged in?