Hi

I have a log in script that if successful starts a session. When you enter the correct info it days that you are logged in, but when you try to acces a restricted file it says that you are not logged in. If you then log in again it works fine. I am not sure even where to start looking for the problem, is it likely to be in the log in script or in the restricted file?

I start the session at the top of each page so I don't think that is the issue, here is the part of my script that i think is most likely the cause of the problem, if anyone could have a look I'd be very grateful.

$sql="SELECT `active` FROM `users` WHERE `username`='".$username."' AND `password`='".$realp."'";    $search = mysql_query($sql) or die(mysql_error());  
    $match  = mysql_num_rows($search);  

if($match==1)
{
$_SESSION['authenticated'] = true ;
$_SESSION['username']=$_POST['username']; 
$_SESSION['password']=$_POST['password'];
    $url = 'index.php'; // default page for 
    if(isset($_SESSION['url']))
    {
        $url = strip_tags($_SESSION['url']);
        unset($_SESSION['url']);
    }

header("Location: http://website.com/$url");
    exit("<p>Authenticated variable is: " . $_SESSION['authenticated'] . "</p>");
}

Thanks
Gilgil

Recommended Answers

All 13 Replies

Member Avatar for diafol

The session_start() IMO should be placed at the top of each page anyway, whether user is logged in or not, as session data can be used with more than just propagating user ids. Is session_start() at the top of EVERY page in your site?

Hi thanks for the reply, yes it is at the start of every page.

Member Avatar for Zagga

As diafol hinted at, it sounds like your session data is not reaching the restricted page on the first visit.
Have you tried echoing the session variables at the top of the restricted page to see if they are still set?

Bit of a long shot ... what happens if you set the header location to http//www.website.com/$url ?

Hi Zagga I did what I think you meant and echoed the following:

<? echo $_SESSION;
echo $_SESSION['authenticated'];
echo $_SESSION['username'];
echo $_SESSION['password'];
?>

The first the result was:

array
1
correct username
correct password

Not entirely sure what this means? Is there a problem with that?

Is it perhaps that I need to delay it by a second or two, is going to index.php too soon for it to register that the user is logged in?

Thanks
Gilgil

Member Avatar for Zagga

Hi again,

It looks like the session data is getting passed through okay, so it maybe something to do with the restricted page.
Could you post the code that checks whether a user is logged in or not?

Hi thanks for the reply, one of the restricted pages has the following code:

<?php
session_start();  
if(isset($_SESSION['authenticated']))
{ 
include 'accountadmin.php';
 }
else
{echo 'You are not currently logged in, you must <br> <a href="/login.php\">Log In</a> to see this page.'; }

?>

And on first attempt it echos the you must be logged in part, but on second attempt it includes accountadmin.php

Other pages are similar but have if(!isset... and then a header to a page telling them to login.

Hi I still haven't got this sorted, so have posted everything I think is relevant below, if anyone can spot what is wrong I'd be very grateful! (Some of the html is outdated but just want to get it all working first).

Login.php:

<?phpsession_start();
error_reporting(E_ALL ^ E_NOTICE);
 if(isset($_SESSION['authenticated']))
{ 
echo 'You are already logged in as:';
echo $username;
echo '<a href="logout.php">Logout</a>';
 }


else {

$SELF=basename(__FILE__);
$msg='';


if(isset($_POST['submit']) && isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password']))
{  
    $link = mysql_connect('' '' '') or die('Could not connect: ' . mysql_error()); 
    mysql_select_db('') or die(mysql_error()); 

    $username = mysql_real_escape_string($_POST['username']);  
    $password = mysql_real_escape_string($_POST['password']);  


$realp = md5($password);

    $sql="SELECT * FROM `users` WHERE `username`='".$username."' AND `password`='".$realp."' AND `active` IS NULL";
    $search = mysql_query($sql) or die(mysql_error());  
    $match  = mysql_num_rows($search);  



if($match==1)
{
$_SESSION['authenticated'] = 1 ;
$_SESSION['username']=$_POST['username']; 
$_SESSION['password']=$_POST['password'];



if (isset($_POST['rememberme'])) {
            /* Set cookie to last 1 year */
setcookie('username', $_POST['username'], time()+60*60*24*365, 'www.example.com');
setcookie('password', $_POST['password'], time()+60*60*24*365, 'www.example.com');
        } else {
            setcookie('username', $_POST['username'], false, 'www.example.com');
            setcookie('password', $_POST['password'], false, 'www.example.com');
        }




    header("Location: http://example.com/index.php");
    exit("<p>Authenticated variable is: " . $_SESSION['authenticated'] . "</p>");
}
else
{ 
    $msg='<p>Login Failed! Please make sure that you enter the correct details and that you have activated your account.</p>';  
}  
}



echo '<html><body><h1>Login Form</h1>';

        if(!empty($msg))
        {
            echo $msg;
        }


echo '<p>Please enter your name and password to login</p>  
        <!-- start sign up form -->  
        <form action="login.php" method="post">  
            <div>
                <label for="name">Name:</label>  
                <input type="text" name="username" value="" />
            </div>
            <div>
                <label for="password">Password:</label>
                <input type="password" name="password" value="" />
            </div>
   Remember Me: <input type="checkbox" name="rememberme" value="1"><br>



            <div><input type="submit" name="submit" class="submit_button" value="Login" /></div>
        </form>  
<a href="http://www.example.com/forgot.php">Forgot Password?</a><br>
<a href="http://www.example.com/register.php">Register here</a>

</body>
</html>';
echo $username;
echo $_SESSION['username'];
echo $_SESSION['authenticated'];
}
?>

Index.php (directed here after successful login)
Code:

<?php 
session_start();
if(isset($_SESSION['authenticated']))
{ 
include 'usermenu.php';
 }
else
{echo 'You are not currently logged in <br> <a href="login.php">Log In</a>'; }

?>
<html>
<body>




</body>
</html>

Usermenu.php (included if logged in)

Code:

<? echo $_SESSION;
echo $_SESSION['authenticated'];
echo $_SESSION['username'];
echo $_SESSION['password'];
?>
You are logged in as <? echo $username ?>  
<a href="myaccount.php">My Account</a>
<a href="logout.php">Log Out</a>

Logout.php
Code:

<?php
session_start();  
if(isset($_SESSION['authenticated'])) 
    unset($_SESSION['authenticated']); 


if(isset($_SESSION['username'])) 
    unset($_SESSION['username']); 


if(isset($_SESSION['password'])) 
    unset($_SESSION['password']); 


$past = time() - 100;
setcookie('username', $_POST['username'], $past, 'www.example.com');
setcookie('password', $_POST['password'], $past, 'www.example.com');


session_destroy();


if(isset($_SESSION['authenticated']))
{ 
echo 'logout unsuccessful';
 }
elseif (isset($_COOKIE['username']))
{
echo 'cookie not removed';
}
else
{
echo 'logout successful';
}


echo $_COOKIE["username"];




echo $_SESSION['authenticated'];
echo $_SESSION['username'];
echo $_SESSION['password'];
?> 
<html>
<body>
Return to <a href="index.php">home page</a>
</body>
</html>

I think this is all the relevant files, myaccount.php accesses mysql db and takes values etc. from there but I don't think there is a problem with that.

Sorry there is so much to look at, but if you could work out what has gone wrong I would be very grateful

Member Avatar for Zagga

Hi again,

The only problem I can see is the very first line of login.php
<?phpsession_start(); should be 2 seperate lines.

<?php
session_start();

It may just be a copy&paste error but I can't see any other errors in the code.
If you are still having problems you will need to do some debugging by sprinkling your code with var_dump and echo statements to see where you are losing the session data.

Hi thanks, yes that was a copy and past error, I have narrowed the problem down now: when you log in it checks with MySQL etc. and that works fine, on successful login you are directed to a page (index.php here but I have changed to see if it is a problem with index.php only but it isn't) once on that page it says you aren't logged in, however if you then click on a link on that page, whatever page you get to next the log in works, so it just takes the user one click of a link for it to work.

Any ideas why this is and how to solve it?

Thanks

Member Avatar for Zagga

I just noticed you have used the short tag <? to open php in usermenu.php. If your server doesn't have short tags enabled it won't process the code as PHP. Change the tag to <?PHP and see if that helps.

Thanks for the reply, the short tags do appear to be working. I put in a meta equiv refresh between login and index.php to see if that helps but it doesn't, so it seems that only clicking on makes the session work. I really don't understand why, there doesn't seem to be any explanation.

An alternative would be to incorporate a link into the login process but without the user realising that its because I'm incompetent ha and making it seem natural, any ideas how to do that?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.