Hi

I am having problems with authenticating session. I moved this over from a different site where I was testing it and didn't change anything but now it doesn't seem to be working.

The site connects to the MySQL data base and if the info is wrong it says so. However if the info is right it takes me back to the previous page, but without the session being authenticated, and so the logged in menu doesn't appear. I am not sure what I am doing wrong.

Here is the session start code from login page if login info is correct

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']);
	}

And here is the part that should check to see if a user is logged in:

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

Thanks for any help.

Hi gilgil2

Have you write in the start of page
session_start(); ? to check session value.

Ye I have that but it still doesn't work... I have no idea why

Why you use comparison operator(==) on line 3?

$_SESSION['authenticated']==true;

It should be

$_SESSION['authenticated']=true;

Hi, thanks, I did have just = but changed it and forgot to change back.

I have tried all this and it still doesn't work. However I have narrowed it down a little.

If I open up usermenu.php then I do appear to be logged in, so I think it is something to do with the include, any ideas?

Here is the full code, really struggling

Here is the login page:

<?php

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

 


if(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']);  
 
	$sql="SELECT `active` FROM `users` WHERE `username`='".$username."' AND `password`='".$password."'";
    $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']);
	}

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


	header("Location: http://web.com/$url");
	exit;
}
else
{ 
    $msg='<p>Login Failed! Please make sure that you enter the correct details and that you have activated your account.</p>';  
}  


?>          
<html>
<body>
        <h1>Login Form</h1>
		<?php 
		if(!empty($msg))
		{
			echo $msg;
		}
		?>
        <p>Please enter your name and password to login</p>  
        <!-- start sign up form -->  
        <form action="<?php echo $SELF; ?>" 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" class="submit_button" value="Login" /></div>
        </form>  
<a href="http://www.web.com/forgot.php">Forgot Password?</a><br>
<a href="http://www.web.com/register.php">Register here</a>
 
</body>
</html>

Here is an example of another page:

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


</body>
</html>

I have no idea what is going on so any help would be appreciated

Member Avatar for Zagga

Hi gilgil2,

you need to use session_start(); at the top of every page that uses $_SESSION variables, including your login page.

Thanks for the reply, I've just tried that but it still isn't working.

Any other comments will be very appreciated, soon I won't have much hair left!

Member Avatar for Zagga

Hi again,

Ok, so you enter correct login details.
Are you redirected to the correct page(index.php)? If so, are you shown the "You are not currently logged in" message.

Hi,

Yes that is what happens. Whereas if I put in the incorrect details then it tells me I have.

So it is communication with MySQL correctly, but not registering the session, although it did when I used it on a test site. Very confused

Member Avatar for Zagga

On line 27 of the login page, instead of setting the 'authenticated' variable to true, try setting it to a text value, your name for example.

Then, add the following code to line 46 and see what is displayed.

exit("<p>Authenticated variable is: " . $_SESSION['authenticated'] . "</p>");

Still the same outcome... I appreciate you trying to help!

Member Avatar for Zagga

Does it echo the correct variable (whatever you set in line 27)?

No it doesn't, nothing different happens, I replaced true with gilgil

Member Avatar for Zagga

The extra line of code I mentioned should have stopped the script and echoed a message. If it didn't do this then the the if($match==1) statement on line 25 is NOT returning 1 like we hope.
This means it is either returning no records, or more than 1 record.

Try adding the following to line 24 of the login page.

exit("<p>Record matches: " . $match . "</p>");

This should stop the script and echo the number of matched database records (matching usernames and passwords).

Hi, if I put it on line 24 it just says 'record matches:' but if I put it on 26 it says 'record matches: 1'

Member Avatar for Zagga

Can you post the code as you have it now please, so I can check my line numbers?

<?php
session_start();

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

 


if(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']);  
 
	$sql="SELECT `active` FROM `users` WHERE `username`='".$username."' AND `password`='".$password."'";
    $search = mysql_query($sql) or die(mysql_error());  
    $match  = mysql_num_rows($search);  
 
}

 
if($match==1)
{

exit("<p>Record matches: " . $match . "</p>");

	$_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']);
	}

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


	header("Location: http:///$url");
	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>';  
}  


?>          
<html>
<body>
        <h1>Login Form</h1>
		<?php 
		if(!empty($msg))
		{
			echo $msg;
		}
		?>
        <p>Please enter your name and password to login</p>  
        <!-- start sign up form -->  
        <form action="<?php echo $SELF; ?>" 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" class="submit_button" value="Login" /></div>
        </form>  
<a href="http:///forgot.php">Forgot Password?</a><br>
<a href="http:///register.php">Register here</a>
 
</body>
</html>
Member Avatar for Zagga

So with the exit statement on line 30 it says 'Record matches: '? What if you place it on line 23?

Sorry, on both lines 30 and 23 it says 'record matches: 1'

Yo, I got the same problem a couple weeks ago.
Add this

error_reporting(E_ALL ^ E_NOTICE);

Just bellow your session_start();
It should work like a charm.

Thank you! For anyone who comes back to this thread, that worked perfectly!

Can you explain why?

No problem, well I will try my best :).
This is the default value set in php.ini. As you might know PHP has many levels of error. Using this command will basically report all errors except E_NOTICE.
For example "Why does this matter to you? Because if you make a single mistake, like using a misspelled variable, you won't know about it! You might do something like:
$x = $varable;
by accident, just a simple typo. If you have E_NOTICE enabled, you'll get a complaint and can fix it right away. If you don't, you've introduced a hard-to-find bug."
The quote is from http://randyfay.com/node/76.

Went through the code bit by bit, edited a few bits but the only thing i saw that would make it not work is the cookies are set for "www.web.com" and the header redirect goes to "web.com"

<?php
$SELF=basename(__FILE__);
$msg='';
if(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']);
	
	$sql="SELECT `active` FROM `users` WHERE `username`='".$username."' AND `password`='".$password."'";
	$search = mysql_query($sql) or die(mysql_error());
	if($search !== false && mysql_num_rows($search) > 0){
		$match = true;
	}else{
		$match = false;
	}
}  

if($match){
	$_SESSION['authenticated'] = true;
	$_SESSION['username'] = $username;
	//bad idea to set password in the session?
	//$_SESSION['password']=$_POST['password'];
	$url = 'index.php'; // default page for 
	if(isset($_SESSION['url'])){
		$url = strip_tags($_SESSION['url']);
		unset($_SESSION['url']);
	}
	
	if(isset($_POST['rememberme'])){
		/* Set cookie to last 1 year */
		setcookie('username', $_POST['username'], time()+60*60*24*365, 'www.web.com');
		setcookie('password', $_POST['password'], time()+60*60*24*365, 'www.web.com');
	}else{
		setcookie('username', $_POST['username'], false, 'www.web.com');
		setcookie('password', $_POST['password'], false, 'www.web.com');
	}
	header("Location: http://www.web.com/$url");
	exit;
}else{ 
    $msg='<p>Login Failed! Please make sure that you enter the correct details and that you have activated your account.</p>';
}
?>          
<html>
<body>
	<h1>Login Form</h1>
	<?php
	if(!empty($msg)){
		echo $msg;
	}
	?>
	<p>Please enter your name and password to login</p>
	<!-- start sign up form -->
	<form action="<?php echo $SELF; ?>" 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" class="submit_button" value="Login" />
		</div>
	</form>
	<a href="http://www.web.com/forgot.php">Forgot Password?</a><br/>
	<a href="http://www.web.com/register.php">Register here</a>
</body>
</html>

Damn, 2 pages.

Ha, thanks anyway!

I think This is hiding the errors and Warnings(make them hidden) but not fixing them.Therefore,when anything happened later yyou will be struggled in finding where is this error(s) come from e.g:when using @mysql when trying to access DB.

This might be an odd question, but did you switch your database login credentials to your new site (instead of using the old ones from the test site)

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.