Jump to content

Why is logged in status not getting set?


twilitegxa

Recommended Posts

I have the following log in script, but for some reason it's not setting the logged in state to logged in. Can anyone help with why?

 

 


<?php


$user_area_location = 'account.php'; // Location of the user area
# #
$error = array();
if(isset($_GET['action'])) {
switch($_GET['action']) {
case 'logoff':
unset($_SESSION['loggedIn']);
array_push($error, 'You were logged off.');
break;
}
}
if(!$error) {
if(empty($_POST['username'])) { array_push($error, 'You didn\'t supply a username'); }
if(empty($_POST['password'])) { array_push($error, 'You didn\'t supply a password'); }
}
if(!$error){
$result = @mysql_query('SELECT username, email, name FROM `users` WHERE username = \''.mysql_real_escape_string($_POST['username']).'\' AND password = \''.mysql_real_escape_string(md5($_POST['password'])).'\'');
if($row = @mysql_fetch_array($result)) {
$_SESSION['loggedIn'] = true;
$_SESSION['userName'] = $row['username']; 
$_SESSION['userMail'] = $row['email'];
$_SESSION['name'] = $row['name'];
header('Location: '.$user_area_location);
die('<a href="'.$user_area_location.'"> Go to your user account</a> or go back to <a href=choose_character.php>choose_character.php</a>');
}else{
array_push($error, 'The username or password you provided were not correct');
}
}
?>


<table cellspacing="2" cellpadding="0" border="0">
<form method="post" action="login.php">
<tr>
<td>Username:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Login!" /> <a href="forgot.php">I forgot my username or password</a></td>


</tr>
</form>
</table>


<?php if(isset($error) && $error) { ?>
<div id="error2">
<ul><?php foreach($error as $key => $value) echo '<li>'.$value.'</li>'; ?></ul>
<><?php } ?>

 

 

I have included the form that is supposed to log the user in as well. Can anyone help me figure out why it's not logging the user in? Every time I try to log in, it just says the username and password were incorrect.

Link to comment
Share on other sites

Now it is simply taking the error message out and staying or redirecting back to the login page, but with no input boxes to log in with, but also with no logged in status set. I can't understand what I am doing wrong. :-(

Link to comment
Share on other sites

does the $user_area_location echo out ok? if it does try poping the exit after the die line and see if it brings up the link.  I think if you echo out the session variables you should find that they are ok.  that it is getting stuck on the header line makes me assume that the logig for the if statement is working ok.

Link to comment
Share on other sites

You are right. When I log in, it will display the logged in status if I echo it as well as the user location. But why won't it show the logged in status where I have it set? I am using a template, and I have the logged in status showing by including the php page. Here is the php page I have that is supposed to display it, maybe you can help with it then:

 

 


<div id="log">
<?php
if (isset($_SESSION['loggedIn']) == 1) {
?>
<p>Welcome, <?php echo $_SESSION['userName'] ?> (<a href="login.php?action=logoff" title="Log Out">Log Out</a>)</p>
<?php
} else {
?>
<p>Please <a href="login.php">log in</a></p>
<?php } ?>
<>

 

 

Plus, it's still not redirecting to the user page for whatever reason :-(

Link to comment
Share on other sites

If you're using sessions, you need to add session_start at the top of your file. Make sure it's at the top of the account.php page too.

 

what output did you get from the echos on the session variables and the $user_area_location? does the header work if you put it as

header('Location: acount.php');

404. :P

Link to comment
Share on other sites

Yes, it outputs account.php when I echo the $user_area_location, and i added the session start to the include that connects to my database which is included in my template page. That should include it in each page shouldn't it?

 

 

Oh, I tried adding the session start to the individual login page and now the logged in status shows. I guess I do have to put it on each page instead of just including it in template.

 

 

But still, my page redirect isn't working. Any suggestions why?

Link to comment
Share on other sites

The problem I'm having now is that the header redirect isn't working and my logout isn't working right. When I login, it stays on the log in page instead of redirecting, and when I log out, it stays on the login page as well. Any help?

Link to comment
Share on other sites

If you're using sessions, you need to add session_start at the top of your file. Make sure it's at the top of the account.php page too.

 

what output did you get from the echos on the session variables and the $user_area_location? does the header work if you put it as

header('Location: acount.php');

404. :P

Link to comment
Share on other sites

<?php
session_start(); // need this to use sessions

$user_area_location = 'account.php'; // Location of the user area
# #
$error = array();
if(isset($_GET['action'])) {
switch($_GET['action']) {
case 'logoff':
unset($_SESSION['loggedIn']);
array_push($error, 'You were logged off.');
break;
}
}
if(!$error) {
if(empty($_POST['username'])) { array_push($error, 'You didn\'t supply a username'); }
if(empty($_POST['password'])) { array_push($error, 'You didn\'t supply a password'); }
}
if(!$error){
$result = @mysql_query('SELECT username, email, name FROM `users` WHERE username = \''.mysql_real_escape_string($_POST['username']).'\' AND password = \''.mysql_real_escape_string(md5($_POST['password'])).'\'');
if($row = @mysql_fetch_array($result)) {
$_SESSION['loggedIn'] = true;
$_SESSION['userName'] = $row['username']; 
$_SESSION['userMail'] = $row['email'];
$_SESSION['name'] = $row['name'];
header('Location: '.$user_area_location);
die('<a href="'.$user_area_location.'"> Go to your user account</a> or go back to <a href=choose_character.php>choose_character.php</a>');
}else{
array_push($error, 'The username or password you provided were not correct');
}
}
?>


<table cellspacing="2" cellpadding="0" border="0">
<form method="post" action="login.php">
<tr>
<td>Username:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Login!" /> <a href="forgot.php">I forgot my username or password</a></td>


</tr>
</form>
</table>


<?php if(isset($error) && $error) { ?>
<div id="error2">
<ul><?php foreach($error as $key => $value) echo '<li>'.$value.'</li>'; 
/* could use echo '<li>' . implode('</li><li>', $error) . '</li>'; here */
?></ul>
<><?php } ?>

 

 

I have included the form that is supposed to log the user in as well. Can anyone help me figure out why it's not logging the user in? Every time I try to log in, it just says the username and password were incorrect.

 

Link to comment
Share on other sites

I have included the session_start() on the login page, but the logged in status doesn't show when the user logs in and doesn't change when they log out. What happens is when the user logs in, it displays this part of the code:

 

 

die('<a href="'.$user_area_location.'"> Go to your user account</a> or go back to <a href=choose_character.php>choose_character.php</a>');

 

 

Then the logged in status does not update until the user navigates to another page. Also, when the user logs out, it doesn't show the updated logged in status, as it stays on the login page, and just tells them they have logged out, but when they navigate to another page, they are shown to be logged out. Any help?

Link to comment
Share on other sites

<?php
session_start();

define('USER_AREA_LOCATION', 'account.php');

$errors = array();
$action = isset($_GET['action']) ? $_GET['action'] : false;

switch($action)
{
case 'logoff':
	session_destroy();
	header('Location: ' . $_SERVER['PHP_SELF'] . '?action=logoutmsg');
break;

case 'logoutmsg':
	$errors[] = 'You have sucessfully logged out.';
break;
}

if ( isset($_POST['submit']) )
{

if ( !isset($_POST['username']) )
{
	$errors[] = 'You must supply a username to login.';
}

if ( !isset($_POST['password']) )
{
	$errors[] = 'You must supply a password to login.';
}

if ( empty($errors) )
{

	$query = "SELECT username, email, name FROM `users` WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . md5($_POST['password']) . "' LIMIT 1";
	$result = mysql_query($query) or trigger_error("Error with query on line " . __LINE__ . "<br >MySql Error: " . mysql_error(), E_USER_ERROR);

	if( mysql_num_rows($result) !== 0 )
	{
		$row = mysql_fetch_assoc($result);

		$_SESSION['loggedIn'] = true;
		$_SESSION['userName'] = $row['username']; 
		$_SESSION['userMail'] = $row['email'];
		$_SESSION['name']     = $row['name'];

		header('Location: ' . USER_AREA_LOCATION);

		die('<a href="' . USER_AREA_LOCATION . '">Go to your user account</a> or go back to <a href="choose_character.php">choose_character.php</a>');

	}
	else
	{
		$errors[] = 'The username/password you provided did not match any account.');
	}
}
}
?>
<table cellspacing="2" cellpadding="0" border="0">
<form method="post" action="login.php">
<tr>
<td>Username:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Login!" /> <a href="forgot.php">I forgot my username or password</a></td>
</tr>
</form>
</table>
<?php
if (isset($errors) && !empty($errors))
{
echo "
<div id=\"error2\">
  <ul><li>" . implode('</li><li>', $errors) . "</li></ul>
</div>";
}
?>

 

//EDIT

Added logout code

Link to comment
Share on other sites

If your header() redirect is not working (i.e. you are actually seeing the output being sent to the browser after the redirect), you likely have content being output to the browser before the header() statement. Are you developing and debugging your code on a system with error_reporting set to E_ALL and display_errors set to ON in your master php.ini (so that fatal parse errors are displayed too) so that php will help you?

Link to comment
Share on other sites

Andy-H:

 

The code you suggested just outputs a blank page when I navigate to the login page, so I cannot test it.

 

PFMaBiSmAd:

I'm not sure if I have my error reporting on. Can you tell me how to check and turn it on? I'm using MAMP, so I'll have to look for the php.ini page. I'm not sure what it was set to as its default.

Link to comment
Share on other sites

The code Andy-H posted contains a fatal parse error (which will let you test if you successfully turn on the two settings I suggested.) Fatal parse errors result in blank pages when the error_repoting/display_errors settings are not the suggested values (for development/debugging.)

 

It is also using !isset() for the name/password form fields, which won't work because the form fields will be set simply because they exist in the form (your original code was correctly using empty().)

Link to comment
Share on other sites

Here's a cleaned up version:

 

<?php

$user_area_location = 'account.php'; // Location of the user area
$error = array();
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'logoff':
            unset($_SESSION['loggedIn']);
            array_push($error, 'You were logged off.');
            break;
    }
}

if (!$error) {
    if (empty($_POST['username'])) {
        array_push($error, 'You didn\'t supply a username');
    }
    if (empty($_POST['password'])) {
        array_push($error, 'You didn\'t supply a password');
    }
    
    function filterUsername($username) {
        return preg_replace('/[^a-z]/i', '', $username);
    }
    
    function filterPassword($password) {
        return preg_replace('/[^a-z0-9]/i', '', $password);
    }
    
    $username = filterUsername($_POST['username']);
    $password = filterPassword($_POST['password']);
    $result = mysql_query("SELECT username, email, name FROM `users`
        WHERE username = '$username' AND password = md5('$password')";
    if (false !== $result && mysql_num_rows($result)) {
        $row = mysql_fetch_assoc($result);
        $_SESSION['loggedIn'] = true;
        $_SESSION['userName'] = $row['username'];
        $_SESSION['userMail'] = $row['email'];
        $_SESSION['name'] = $row['name'];
        header('Location: ' . $user_area_location);
        exit(0);
    } else {
        array_push($error, 'The username or password you provided were not correct');
    }
}
?>


<table cellspacing="2" cellpadding="0" border="0">
    <form method="post" action="login.php">
        <tr>
            <td>Username:</td>
            <td><input type="text" name="username"/></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" name="submit" value="Login!"/> <a href="forgot.php">I forgot my username or
                password</a></td>


        </tr>
    </form>
</table>


<?php if (!empty($error)): ?>
<div id="error2">
    <ul>
    <?php foreach ($error as $key => $value): ?>
        <li><?php echo '<li>' . $value . '</li>'; ?></li>
    <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

 

@twilitegxa md5($password) won't help you as it leaves you vulnerable to an attack (Rainbow Table) and you should instead use a salt, like:

 

md5( concat( password_salt, md5( '$password' ) ) )

Link to comment
Share on other sites

<?php
error_reporting(E_ALL);

ini_set('display_errors', 'On');

session_start();

define('USER_AREA_LOCATION', 'account.php');

$errors = array();
$action = isset($_GET['action']) ? $_GET['action'] : false;

switch($action)
{
   case 'logoff':
      session_destroy();
      header('Location: ' . $_SERVER['PHP_SELF'] . '?action=logoutmsg');
   break;

   case 'logoutmsg':
      $errors[] = 'You have sucessfully logged out.';
   break;
}

if ( isset($_POST['submit']) )
{

   if ( !empty($_POST['username']) )
   {
      $errors[] = 'You must supply a username to login.';
   }
   
   if ( !empty($_POST['password']) )
   {
      $errors[] = 'You must supply a password to login.';
   }

   if ( empty($errors) )
   {

      $query = "SELECT username, email, name FROM `users` WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . md5($_POST['password']) . "' LIMIT 1";
      $result = mysql_query($query) or trigger_error("Error with query on line " . __LINE__ . "<br >MySql Error: " . mysql_error(), E_USER_ERROR);
      
      if( mysql_num_rows($result) !== 0 )
      {
         $row = mysql_fetch_assoc($result);

         $_SESSION['loggedIn'] = true;
         $_SESSION['userName'] = $row['username']; 
         $_SESSION['userMail'] = $row['email'];
         $_SESSION['name']     = $row['name'];

         header('Location: ' . USER_AREA_LOCATION);

         die('<a href="' . USER_AREA_LOCATION . '">Go to your user account</a> or go back to <a href="choose_character.php">choose_character.php</a>');
         
      }
      else
      {
         $errors[] = 'The username/password you provided did not match any account.';
      }
   }
}
?>
<table cellspacing="2" cellpadding="0" border="0">
<form method="post" action="login.php">
<tr>
<td>Username:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Login!" /> <a href="forgot.php">I forgot my username or password</a></td>
</tr>
</form>
</table>
<?php
if (isset($errors) && !empty($errors))
{
echo "
<div id=\"error2\">
  <ul><li>" . implode('</li><li>', $errors) . "</li></ul>
<>";
}
?>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.