Jump to content

Recommended Posts

Hey PHP Gurus...

 

I'm dyin' here...I have a login page (see code below) and a database row called "logged_in" that I give a value of "1" on successful login so I can display (with an if statement) when more than on ADMINISTRATOR is logged in...

 

All of this works like a charm...but for the life of me, I can't get the UPDATE to change the "1" to a "0" for the person logging out...everything I've tried either logs out EVERYONE logged in or it simply doesn't work...

 

This is the bulk of the page code...the line in BOLD or THE SECOND QUERY (if the code is not bold) is where I'm having the problem...

 

==================================

<?php
if (logged_in()) {
	redirect_to("content.php");
}	
include_once("includes/form_functions.php");

//start form processing
if (isset($_POST['submit'])) { //from has been submited
	$errors = array();

	//perform validations on the form data
	$required_fields = array('username', 'password');
	$errors = array_merge($errors, check_required_fields($required_fields, $_POST));

	$fields_with_lengths = array('username' => 30, 'password' => 30);
	$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));

	$username = trim(mysql_prep($_POST['username']));
	$password = trim(mysql_prep($_POST['password']));
	$hashed_password = sha1($password);

	if (empty($errors)) {
		//check database to see if username and the hashed password exists
		$query = "SELECT id, username ";
		$query .= "FROM users ";
		$query .= "WHERE username = '{$username}' ";
		$query .= "AND hashed_password = '{$hashed_password}' ";
		$query .= "LIMIT 1";
		$result_set = mysql_query($query);
		confirm_query(result_set);
		if (mysql_num_rows($result_set) == 1) {
			//username-password authenticatied
			//and only one match
			$found_user = mysql_fetch_array($result_set);
			$_SESSION['user_id'] = $found_user['id'];
			$_SESSION['username'] = $found_user['username'];
    
			//set logged_in to ONE if successful login
			$query = "UPDATE users SET logged_in = '1' WHERE username = '{$username}'";
			$result = mysql_query($query);
			confirm_query(result);
    				
			redirect_to("content.php");
		} else {
			//username-password combo was not found
			$message = "Username and password combination was not found in the database.<br />
							   Make sure your CapsLock key is off and try again.";
		}

	} else {
		if (count($errors) == 1) {
			$message = "There was an error in your submission.";
		} else {
			$message = "There were " . count($errors) . " errors in your submission.";
		}
	}

} else {//form has not been submitted
	if (isset($_GET['logout']) && $_GET['logout'] == 1) {
    
			//set logged_in to ZERO on user logout	
			//THIS WORKS IF I SET A SPECIFIC USERNAME...NEED TO PULL SESSION USERNAME SOMEHOW
			[b]mysql_query("UPDATE users SET logged_in = '0' WHERE username = '{$username}'");[/b]				
		$message = "You are now logged out.";    			
	}
	$username = "";
	$password = "";
}
?>

==================================

 

...somebody, PLEASE throw me a bone!

 

Thanks in advance for taking a look at my code...

 

Link to comment
https://forums.phpfreaks.com/topic/243982-how-to-find-current-user/
Share on other sites

I use a redirect_to("content.php"); and using $_SESSION['username'] works for all of the logged_in users...and on that page with the IF STATEMENT I can put a BIG RED BORDER around the names of other adiminstrators that log in...

 

Actually, any page where I call the function confirm_login()...I can display the $_SESSION['with any of the row info I want'];

 

I just can't seem to change the 1 to a 0 for a single user on log out...

 

Any ideas where I might look "if the problem is else where?"

well, to start with, your code will only work if the users actually press your logout button. What if they login and then just close the browser?

 

you should set a timestamp for each login, and then check their activity at regular intervals so you can decide how and when they get logged out.

NO, not included on another file...its run on login and redirected to content.php and run on logout...so basically this page processes the log in and log out process...although there is a logout.php with:

 

<?php require_once("includes/functions.php"); ?>
<?php
session_start();
$_SESSION = array();
if(isset($_COOKIE[session_name()])) {
	setcookie(session_name(), ' ', time()-50000, '/');
}
session_destroy();
redirect_to("login.php?logout=1");
?>

 

...did I answer your question?

that logout page is also not setting the variable to 0 in the database. Why do you have 2 different logouts? and why on earth would you put login and logout in the same file? what do you even call that file? login? logout? login-logout? it must be confusing.

 

Just create a nice little logout page, and always use the same one. Include mysql statement to reset the database variable in it, before you reset the session array.

...the session is started...with <?php require_once("includes/session.php"); ?> which contains the code below...

<?php 
session_start();	
function logged_in() {
	return isset($_SESSION['user_id']);
    session_regenerate_id();
}	
function confirm_logged_in() {
	if (!logged_in()) {
		redirect_to("login.php");
	}
}
?>

ok, so instead of a 1 and a 0, consider a 0 and a timestamp. if you grab the users timestamp (on login to start with) and then on each activity ( just by using time ), you can then decide whatever you want. Say you want everyone to be logged out after 5 minutes of inactivity... hang on... Just the other day there was another post about this, check here:

 

http://www.phpfreaks.com/forums/index.php?topic=340233.msg1603821#msg1603821

...the session is started...with <?php require_once("includes/session.php"); ?> which contains the code below...

<?php 
session_start();	
function logged_in() {
	return isset($_SESSION['user_id']);
    session_regenerate_id();
}	
function confirm_logged_in() {
	if (!logged_in()) {
		redirect_to("login.php");
	}
}
?>

You have to start the session every time you load a page. That's why I asked if the initial script you posted was run as an include or independent file. From what I can see from your code someone clicks the logout button and is then sent to the page you linked in your original post. Because it's a new page you need to start the session again.

Vel,

Here is the entire page code...and the session is started at the top of the page...my initial post indicated the BULK of the page code...

 

<?php require_once("session.php"); ?>
<?php require_once("connection.php"); ?>
<?php require_once("functions.php"); ?>
<?php
if (logged_in()) {
	redirect_to("content.php");
}	
include_once("includes/form_functions.php");

//start form processing
if (isset($_POST['submit'])) { //from has been submited
	$errors = array();

	//perform validations on the form data
	$required_fields = array('username', 'password');
	$errors = array_merge($errors, check_required_fields($required_fields, $_POST));

	$fields_with_lengths = array('username' => 30, 'password' => 30);
	$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));

	$username = trim(mysql_prep($_POST['username']));
	$password = trim(mysql_prep($_POST['password']));
	$hashed_password = sha1($password);

	if (empty($errors)) {
		//check database to see if username and the hashed password exists
		$query = "SELECT id, username ";
		$query .= "FROM users ";
		$query .= "WHERE username = '{$username}' ";
		$query .= "AND hashed_password = '{$hashed_password}' ";
		$query .= "LIMIT 1";
		$result_set = mysql_query($query);
		confirm_query(result_set);
		if (mysql_num_rows($result_set) == 1) {
			//username-password authenticatied
			//and only one match
			$found_user = mysql_fetch_array($result_set);
			$_SESSION['user_id'] = $found_user['id'];
			$_SESSION['username'] = $found_user['username'];
    
			//set logged_in to ONE if successful login
			$query = "UPDATE users SET logged_in = '1' WHERE username = '{$username}'";
			$result = mysql_query($query);
			confirm_query(result);
    				
			redirect_to("content.php");
		} else {
			//username-password combo was not found
			$message = "Username and password combination was not found in the database.<br />
							   Make sure your CapsLock key is off and try again.";
		}

	} else {
		if (count($errors) == 1) {
			$message = "There was an error in your submission.";
		} else {
			$message = "There were " . count($errors) . " errors in your submission.";
		}
	}

} else {//form has not been submitted
	if (isset($_GET['logout']) && $_GET['logout'] == 1) {
    
			//set logged_in to ZERO on user logout	
			//THIS WORKS IF I SET A SPECIFIC USERNAME...NEED TO PULL SESSION USERNAME SOMEHOW
			$username = $_SESSION['user_id'];
			mysql_query("UPDATE users SET logged_in = '0' WHERE username = '$username'");

		$message = "You are now logged out.";    			
	}
	$username = "";
	$password = "";
}
?>
<?php include("includes/header.php"); ?>
<!-- start sidebar -->
<div id="login_sidebar"></div>  
<!-- end sidebar -->
<!-- start main content -->
<div id="login_content">
	<div id="content_top">
              <h2 style="margin:0 0 10px 10px;">Login Page</h2>
              <?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
              <?php if (!empty($errors)) { display_errors($errors); } ?>
              <form name="login" method="post" action="login.php">
                <table width="100%" border="0" cellspacing="5" cellpadding="5">
                  <tr>
                    <td width="100">User name </td>
                    <td><input type="text" name="username" maxlength="30" style="width:200px;" value="<?php echo htmlentities($username); ?>" /></td>
                  </tr>
                  <tr>
                    <td>Password </td>
                    <td><input type="password" name="password" maxlength="30" style="width:200px;" value="<?php echo htmlentities($password); ?>" /></td>
                  </tr>
                  <tr>
                    <td> </td>
                    <td><input type="submit" name="submit" value="Log In" /></td>
                  </tr>
                  <tr>
                    <td> </td>
                    <td>  If you have logged out, <a href="login.php">click here</a> to log in again <a href="../index.php">or go back to homepage</a>. </td>
                  </tr>
                </table>
             </form>
    </div>
    <!-- end content area div -->
</div>
<!-- end navigation and content div -->
<?php include("footer.php"); ?>

OK, add

ini_set ("display_errors", "1");
error_reporting(E_ALL);

to the top of the page. then change your code to:

 

<?php ...
//set logged_in to ZERO on user 
//THIS WORKS IF I SET A SPECIFIC USERNAME...NEED TO PULL SESSION USERNAME SOMEHOW
$username = $_SESSION['username'];
$sql = "UPDATE `users` SET logged_in = 0 WHERE username = '$username'"
if(!mysql_query($sql))
die('Error updating logged out user. ' . mysql_error() . '<br>SQL: ' . $sql);

See if it outputs any error.

...probably did exactly what you expected...same error for line 69 and 70 and the error string returned nothing...

 

Just showed up as "Session Username: "...

 

I want you to know whether we solve this issue or not, you've put in a great deal of time and appreciate it immensely...

Your welcome :). I get a lot of help here too and like to give back when I can.

 

The problem is there is nothing in $_SESSION['username']. Why, I can't tell without seeing all of your code. I suggest you start with session.php and go through to where $_SESSION['username'] should be set and see why it isn't being set.

...why is it availble for the first query above?

 

That's what's really confusing me...the $_SESSION['username'] is available for the query to UPDATE to "1"...which, like I said before...is working like a charm...I can log in as many users as I have browsers installed and each page has the RIGHT name in the welcome...really wearing me down...and I guess by now...you to  :-\

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.