Jump to content

Recommended Posts

Hi all,

 

 

having a spot of bother unsetting a single $_SESSION variable on a login page.

 

Basically, i'm trying to return an error if the login was unsuccessful due to either the username or password was wrong. I set the $_SESSION['invalid'] variable to equal an error message variable $msg within the check login details if statement. Then after i've set it i use a header to redirect back to the page again.

 

then i use the following code to print it to the page:

 

$error_color="#61d0fe";
$errors2 = $_SESSION['invalid'];

if ($errors2) {
echo "<div style='padding-left: 50px; margin-left: auto; margin-right: auto; color:";
echo $error_color;
echo ";'><br>";
echo $errors2;
echo "</div><br><br>";
$errors2="";
unset($_SESSION['invalid']);
}

 

but if i use the above unset($_SESSION['invalid']) line the error message doesn't display at all. It destroys it without it printing on the page.

However, if i leave it out the error message doesn't disappear until the whole session is reset by clearing the browser history or closing the page.

 

This has been bugging me for a few hours now. Is there any way round it??

 

Thanks for your help in advance!

Link to comment
https://forums.phpfreaks.com/topic/189868-_session-help/
Share on other sites

It sounds like your page is being requested twice and you only see the output that occurs on the second request, which is no output because the unset() has cleared the variable.

 

It would take seeing the whole code on the page that is not working and if that page is redirecting to another page, the code on that second page as well.

 

Also, what browser are you testing with (and if it is FF, what debugger add-ons do you have installed) and are you doing any URL rewriting?

Link to comment
https://forums.phpfreaks.com/topic/189868-_session-help/#findComment-1001886
Share on other sites

There isn't a $_SESSION['error']. Do you mean insert it somewhere? How can i then clear that variable?

So make it and set it. $_SESSION['error']=$errors2

Why worry about clearing it. If you somewhere else in your code do $_SESSION['error']=$error3 then it will be that value. If you are really worried for some reason you can simply do $_SESSION['error']='' and empty it.

 

 

HTH

Teamatomic

Link to comment
https://forums.phpfreaks.com/topic/189868-_session-help/#findComment-1001889
Share on other sites

It sounds like your page is being requested twice and you only see the output that occurs on the second request, which is no output because the unset() has cleared the variable.

 

It would take seeing the whole code on the page that is not working and if that page is redirecting to another page, the code on that second page as well.

 

<?php
include('Connections/lh.php');

//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

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

$loginUsername="";
$loginUsername=$_POST['login_username'];
$password="";
$password=$_POST['login_password'];
$errors="";

function validate_email($email) {
return preg_match('/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]+\.[A-Za-z0-9_\-\.]+$/', $email) == 0;
}

if (validate_email($loginUsername) ) {
$errors.="ERROR: Please enter a valid email address in the form of [email protected].<br><br>";
}

if ($password == '')
$errors.="ERROR: Please enter your password.<br><br>";

if ( !$errors ) {
  $MM_fldUserAuthorization = "activated";
  $MM_redirectLoginSuccess = "../LHU/cjproregister.php";
  $MM_redirectLoginFailed = "index2.php";
  $MM_redirecttoReferrer = true;
  mysql_select_db($database_lh, $lh);
  	
  $LoginRS__query=sprintf("SELECT their_username, their_password, activated FROM cjusers WHERE their_username=%s AND their_password=%s",
  GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
   
  $LoginRS = mysql_query($LoginRS__query, $lh) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
    
    $loginStrGroup  = mysql_result($LoginRS,0,'activated');
    
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;	      

    if (isset($_SESSION['PrevUrl']) && true) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
$_SESSION['invalid']="true";
    header("Location: ". $MM_redirectLoginFailed );
  }
  }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- Design by BottyZ -->
<head>
<title>Support Area Login</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="">
<meta name="description" content="">
<link href="../LHU/css/mainltblue.css" rel="stylesheet" type="text/css">
<script src="../LHU/jquery.js" type="text/javascript"></script>
</head>
<!-- ImageReady Slices (Rich Web Visual3.psd) -->
<body>
<script type="text/javascript">
<!--
$(document).ready(function()
{
    $(".defaultText").focus(function(srcc)
    {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    $(".defaultText").blur(function()
    {
        if ($(this).val() == "")
        {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });
    
    $(".defaultText").blur();        
});
//-->
</script>
<?php
		if(preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT'])) {
			include_once( '../LHU/ltbluenavie6.php' );
			} else {
			include_once( '../LHU/ltbluenav.php' );
			}
?>
	<div id="main">
		<div id="maincontentlogin">
		<br>
	<br>
	<h1><img src="http://www.bottyz.co.uk/LHU/images/cjlogin.png" alt="CJ Pro Login Area"></h1>
	<br>
	<br>
<?php

$error_color="#61d0fe";

if ($errors) {
echo "<div style='padding-left: 50px; margin-left: auto; margin-right: auto; color:";
echo $error_color;
echo ";'><br>";
echo $errors;
echo "</div><br><br>";
$errors="";
}

if ($_SESSION['invalid']="true") {
echo "<div style='padding-left: 50px; margin-left: auto; margin-right: auto; color:";
echo $error_color;
echo ";'>ERROR: Invalid Username/Password!</div><br><br>";
$_SESSION['invalid']="";
}

?>
<form style="margin-left: auto; margin-right: auto;" action="<?php echo $loginFormAction; ?>" method="POST" name="LoginFrom">
<div style="margin-left: auto; margin-right: auto;">
<div style="margin: 0 auto; width: 400px;">
<fieldset>
<legend style="color: #61d0fe; font-size: 1.2em;"> Login </legend>
<br>
<div style="padding-left: 40px;">
  <label for="login_username">Email Address: </label>
  <input class="defaultText" type="text" name="login_username" value="<?php echo htmlentities($loginUsername) ?>" tabindex="1">
  <br><br>
  <label for="login_password">Password: </label>
  <input class="defaultText" type="password" name="login_password" tabindex="2">
  <br><br>
  <input type="submit" name="Submit" value="  Login  " tabindex="3">
  <br><br>
</div>
</fieldset>
<br>
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<a href="cjproregister.php"><b>Register Now</b></a>  |  <a href="#"><b>Forgot Password?</b></a></div>
<br>
</div>
</div>
</form>
		<br>
		<br>
		<br>
		</div>
	</div>
<?php
include_once( '../LHU/copyright.php' );
?>
</div>
</body>
</html>

 

 

That is the full page code. I've contained all login functions within that one page. I've tried teamatomic's method to the best of my ability and it didn't change anything. I can't understand it.

 

The above code i've modified from the original snippet i posted and now displays the error regardless. I've echoed the $_SESSION['invalid']  which is for some reason always true.

 

Also, what browser are you testing with (and if it is FF, what debugger add-ons do you have installed) and are you doing any URL rewriting?

 

I'm testing in FF, SAFARI, GC, IE and O. All showing the same. FF has Aadvark and HTML tidy installed.

 

 

Link to comment
https://forums.phpfreaks.com/topic/189868-_session-help/#findComment-1001898
Share on other sites

the page name is index2.php

 

which as you can see...

$MM_redirectLoginFailed = "index2.php";

header("Location: " . $MM_redirectLoginFailed );

 

the header uses index2.php as the name it redirects to upon failure.

 

I've just added exit; after each of the header redirects and still get a constant true session variable.

 

Sorry, if im making a noob mistake or missing something blatantly obvious! I've coded with php plenty before but i've never delved into user authentication until recently, and i'm still trying to get a feel for it.

 

Any more help would be very much appreciated!

Link to comment
https://forums.phpfreaks.com/topic/189868-_session-help/#findComment-1001916
Share on other sites

Aside from the fact that you are redirecting to the same page you are already on (why not just arrange the logic so that you fall-though to the rest of the code on the page), your current problem is because the following is assigning "true" to the session variable, it is not testing if the session variable is equal to "true" -

if ($_SESSION['invalid']="true") {

 

One = sign is an assignment operator. Two == signs is an equal comparison.

 

Link to comment
https://forums.phpfreaks.com/topic/189868-_session-help/#findComment-1001930
Share on other sites

Aside from the fact that you are redirecting to the same page you are already on (why not just arrange the logic so that you fall-though to the rest of the code on the page), your current problem is because the following is assigning "true" to the session variable, it is not testing if the session variable is equal to "true" -

if ($_SESSION['invalid']="true") {

 

One = sign is an assignment operator. Two == signs is an equal comparison.

 

You are a legend! I was staring right at the problem. Thanks for pointing that out, it sometimes takes a fresh eye to see blantant errors when you been looking at a screen for hours.

 

As for rearranging the code so that i don't need to reload the page: I can't see a way in which i could do that? A couple more pointers would be great if you have any.

 

Thanks again!

Link to comment
https://forums.phpfreaks.com/topic/189868-_session-help/#findComment-1001933
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.