How do I sign in to a PHP server to login to a separate application (HTML + JS) using Ajax?

Asked

Viewed 1,025 times

1

I’m making a Hybrid app with Phonegap (using HTML5, CSS and JS only - 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. The login also works in a similar way: the values typed in the inputs are sent to a PHP file on the server, which validates the user and 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 specific password.

Searching about sessions, I saw that they always need to be created and managed on the server side, but I couldn’t think of any way to do that in my case.

How can I create a session for the server-side user when they log in and access the session variables in the Javascript application to, for example, redirect them directly from the #login page to the #Events page, if there is already a valid session, or similarly redirect it from the #Events page to the #login page if there is no valid session and the user is not logged in?

1 answer

0


The way would be yours PHP return session id to the application, in the application store this id to use for next requests.

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 storing the session id and using it in the next requests to pages that require sessions.

Here is an example (pretty basic) of how to recover this id and log in with it (thus rescuing 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 avoid unauthorized access simply create an item in your session when you do the example client authentication:

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

And when you receive a session "id" check that 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!
     */
 }

Although using remote ids to create|recover session data is not the recommended works of good, in case you want to give more security recommend taking a look at PHP Secure Session is an Handler to encrypt session data.

Although outside the scope of the question an easier way to recover session data would be to store it (session) in some database and use a tokem to retrieve it.

I have a little Handler for that which I created from an unanswered doubt here at stackoverflow although it is to MongoDB it is easy to follow the logic and adapt it to MySQL.

  • That’s what I needed. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.