How to create a session on a PHP server to log in to a separate application (HTML + JS) using Ajax?

1

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?

    
asked by anonymous 14.09.2016 / 15:20

1 answer

0

The way it would be your PHP return the id of the session to the application, in the application store this id to use in the next requisitions.

Example PHP :

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) {

        session_start();
        $res = 'true';

    }

    else {

        $res = 'false';

    }

    echo json_encode(array("result" => $res, "sessid" => session_id()));

    break;

In this example your application would be in charge of saving the session id and using it in the next requests to pages that require sessions.

Here is an example (very basic) of how to retrieve this id and log in with it (thus retrieving the information from this session):

 if( isset($_POST['sess_id']) ){
     session_id($_POST['sess_id']);
     session_start();
 }else {
    /**
     caso não tenha sido enviado um post contendo um id de sessão
     redirecionar para ua página de erro!
     */
 }

To prevent unauthorized access simply create an item in your session when you authenticate the client example:

<?php
   // logo após iniciar a sessão
   session_start();
   $_SESSION['CLIENT-AUTH'] = 'true';
   $res = 'true';

And when you receive a session "id" check if that session has such an item:

 if( isset($_POST['sess_id']) ){
     session_id($_POST['sess_id']);
     session_start();

     // verficar se não existe um item
     if(!isset($_SESSION['CLIENT-AUTH']) AND $_SESSION['CLIENT-AUTH'] != 'true'){
        // destruir a sessão e redirecionar
        session_destroy();
        header('Location: página-de-erro.php');
        exit();

        // caso $_SESSION['CLIENT-AUTH'] exista o código corre normalmente
     }
 }else {
    /**
     caso não tenha sido enviado um post contendo um id de sessão
     redirecionar para uma página de erro!
     */
 }

While using remote ids to create | retrieve session data is not recommended, it works fine, if you want to give more security I recommend taking a look at # is a handler for encrypting session data.

While outside the scope of the question, an easier way to retrieve session data would be to store them (the session) in some database and use a token to retrieve it.

I have a small handler for this that I created from an unanswered question here in stackoverflow although it is for MongoDB is easy to follow logic and adapt it to MySQL .

    
14.09.2016 / 16:29