0

I am creating a site that requires a login before you can do anything, the flow for this is as follows:

  1. User inputs username and password then clicks "login"
  2. Username & password is sent to a JavaScript page for jQuery ajax to another php page to be dealt with
  3. The PHP script deals with the request as appropriate and sets a session variable (`user_logged_in`) to either "1" or "0"
  4. Depending on what is returned, the page relocates to the index page or shows a message

My problem is that I use a config file to determine whether or not the user is logged in using this session variable, but for some reason (although the variable is set to 1), the page still says that it is not, the code is as follows:

Main login page:

<?php
require_once 'login_config.php';
$alert = false;
if (isset($_GET['alert']) && $_GET['alert'] == "1")
{
    $alert=true;
}

//$_SESSION['user_logged_in'] = false;

//if ($_SESSION['user_logged_in'] == true)
//{
//    header("Location: /");
//}
?>
<!DOCTYPE html>
<html>

<head>
    <title>GWSAM &raquo; Login</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="styles/login_style.css" />
    <script src="scripts/login/jquery.login.ajax.js"></script>
</head>

<body class="container-fluid">
    <div class="row">
        <div class="col-sm-3"></div>
        <div class="col-sm-6">
            <h1>GWSAM &raquo; Login</h1>
            <?php if ($alert) { ?><p style="text-align: center;" class="alert alert-danger">You must login to access this.</p><?php } ?>
            <table class="table table-condensed table-bordered table-striped">
                <tr>
                    <td>
                        <label for="username">Username</label>
                    </td>
                    <td>
                        <input type="text" name="username" placeholder="Username" class="form-control" id="username" />
                    </td>
                </tr>

                <tr>
                    <td>
                        <label for="password">Password</label>
                    </td>
                    <td>
                        <input type="password" name="password" placeholder="Password" class="form-control" id="password" />
                    </td>
                </tr>

                <tr>
                    <td colspan="2">
                        <input type="hidden" id="http-host" value="<?=$_SERVER['HTTP_HOST']; ?>" />
                        <button id="login" class="form-control btn btn-primary">Login</button>
                    </td>
                </tr>
            </table>
            <div class="row">
                <div class="col-sm-12"id="loading"></div>
            </div>
        </div>
        <div class="col-sm-3"></div>
    </div>
</body>

</html>
<?=var_dump($_SESSION);?>

JavaScript jQuery ajax page:

$( document ).ready( function ()
{
    $( "#login" ).on( "click", function ()
    {
        $.ajax( {
            url: "/scripts/login/files/login.php?username=" + $( "#username" ).val() + "&password=" + $( "#password" ).val(),
            type: "GET",
            success: function ( R )
            {
                if ( R == "true" )
                {
                    document.write( '<meta http-equiv="refresh" content="0;URL=\''+$("#http-host").val()+'\'" />' );
                    window.location.href = $( "#http-host" ).val();
                    return false;
                    //$( "#loading" ).html( '<meta http-equiv="refresh" content="0; URL=index.php" />' );
                    //window.location.href = "index.php";
                    //return;
                }
                $( "#loading" ).html( R );
            },
            beforeSend: function ()
            {
                $( "#loading" ).html( '<p class="alert alert-info" style="text-align: center;">Logging in, please wait.<br /><img src="http://www.iggadget.com/assets/images/loader-1.gif" alt="spinner.gif" height="30" width="30" /></p>' );
            }
        } )
    } );
} );

Ajax page:

<?php

require_once '../../../login_config.php';

function Login($username, $password)
{
    global $link;
    while ($result = mysqli_fetch_assoc($link->query("SELECT `username`, `password`, `active` FROM `users` WHERE `username`='{$username}';")))
    {
        if ($result['active'] == "NO")
        {
            print '<p class="alert alert-danger" style="text-align: center;">User\'s account has been deactived, please contact your network admin</p>';
            $_SESSION['user_logged_in'] = "0";
            return false;
        }
        if ($password == $result['password'])
        {
            $_SESSION['user_logged_in'] = "1";
            return true;
        }
    }
    $_SESSION['user_logged_in'] = "0";
    return false;
}

print Login($_REQUEST['username'], $_REQUEST['password']) ? 'true' : '<p class="alert alert-warning" style="text-align: center;">Cannot login, please try again.</p>';

?>

Config page for the index.php file:

<?php

require_once 'functions/functions.php';
require_once 'functions/database.php';

if (!isset($_SESSION))
    session_start();
$logged_in = isset($_SESSION['user_logged_in']) ? ($_SESSION['user_logged_in'] == "1" ? true : false ) : false;
if (!$logged_in) 
{
    header("Location: login.php");
}
else
{
    //Null action
}

?>

The index page is shown after all is done, but it keeps sending it back to the login page...

I hope this is enough information to go on...

6
  • 1
    Start session before use. on top of php page session_start() Commented Oct 12, 2015 at 11:47
  • @Rahautos, session_start() starts the session...? Commented Oct 12, 2015 at 11:48
  • yes plz start session before use. Commented Oct 12, 2015 at 11:49
  • @Rahautos, I do, please see the main index config file, the login config file is the exact same without the logged in check Commented Oct 12, 2015 at 11:50
  • Move session_start() to the top of every page. Dont test first and then start it, just start it Commented Oct 12, 2015 at 11:51

3 Answers 3

2

First write session_start(); on top of page and try this:

if(isset($_SESSION['user_logged_in'])&&($_SESSION['user_logged_in']==='1'))
{

//if logged in already
}else{

header("Location: login.php");
}
Sign up to request clarification or add additional context in comments.

7 Comments

Wouldn't work as the variable gets set regardless of if it was a successful login or not (true/false, 0/1)
@SamSwift : yea i did not see your full code ..now see
Afraid it did not, please see the answer given by Riggs Folly for what caused the issue. Thank you for your contribution to this :)
@SamSwift : i have edited it aleardy ... did you notice,,, i think there is no difference in his code and mine ,, only the approach is different. anyways nice that you got solution
the difference is the stray piece of code that sets the variable to false before the code that you have amended, the bottom part (where you have changed) is pretty much the same, but it wasn't this that caused the issue :)
|
1

First move session_start() to the top of all pages or at least all pages that use the $_SESSION variable. The best idea is to add it to an include that you include on all pages.

You also have a line in this script that sets $_SESSION['user_logged_in'] = false; just before you test if its got a value, that I assume got added in testing and was not removed.

<?php
session_start();

require_once 'functions/functions.php';
require_once 'functions/database.php';

// this line makes NO SENSE so remove it
//$_SESSION['user_logged_in'] = false;


if ( ! isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] == 0)  {
    header("Location: login.php");
}
else
{
    //Null action
}
?>

3 Comments

Would you believe me if I said the line that makes no sense was causing the problem....
Haha YUP. We all do it from time to time.
Seems to be the small things that we overlook haha, thank you, @RiggsFolly
1

Try this code

<?php
session_start();
require_once 'functions/functions.php';
require_once 'functions/database.php';

$_SESSION['user_logged_in'] = false;

$logged_in = isset($_SESSION['user_logged_in']) ? ($_SESSION['user_logged_in'] == "1" ? true : false ) : false;
if (!$logged_in) 
{
    header("Location: login.php");
    exit;
}
else
{
    //Null action
}

?>

3 Comments

Dont you want to remove the session_start() inside the IF
This has not worked, on top of every PHP page I have put a session_start and still the same issue, and @RiggsFolly, I have also removed it from the if
Now you have a strange hanging if (!isset($_SESSION))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.