user online / offline - NEED HELP

OK, so I’m new to working with php and mysql. I’ve been trying to get a column to update for just ONE row when a user logs in.
What I want is for user_status to update to “1” when the user logs in, then update to “0” when the user logs out. I’ll then use this to show if the user is online or offline. I had something written that was working for a while, but my UPDATE statement kept updating every row instead of just the active session.

Here’s my code and my database …

login.php:
[PHP]

<?php $css = file_get_contents('style.css'); echo $css; ?> <?php function loadIndex(){ echo ""; } ?> <?php require("common.php"); $submitted_username = ''; if(!empty($_POST)) { $query = " SELECT id, username, password, salt, email, UserType, first_name, last_name, city, country, phone, website, interests, birthday, profile_description, photoshop_progress, illustrator_progress, php_progress, user_status FROM users WHERE username = :username LIMIT 1 "; $query_params = array( ':username' => $_POST['username'] ); try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch(PDOException $ex) { die("Failed to run query: " . $ex->getMessage()); } $login_ok = false; $row = $stmt->fetch(); if($row) { $check_password = hash('sha256', $_POST['password'] . $row['salt']); for($round = 0; $round < 65536; $round++) { $check_password = hash('sha256', $check_password . $row['salt']); } if($check_password === $row['password']) { $login_ok = true; } } if($login_ok) { unset($row['salt']); unset($row['password']); $_SESSION['user'] = $row; $LoginMessage='You are currently logged in.'; } else { print("Login Failed."); $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); } } if(isset($_SESSION) AND $_SESSION):?>
    <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>
    <?php 

$TheUserType=htmlentities($_SESSION[‘user’][‘UserType’], ENT_QUOTES, ‘UTF-8’);

if($TheUserType== 3 ){
echo ‘Admin’;
}else{}
?>
| Home
| Edit Account
| Logout
<?php

$TheUserType=htmlentities($_SESSION[‘user’][‘UserType’], ENT_QUOTES, ‘UTF-8’);

if($TheUserType== 1 || 2 || 3 ){
echo ‘| Memberlist’;
echo ’ | ';
include(“user_online.php”);
}else{}
?>

    <?php echo '<br/><br/>';
	echo $LoginMessage; ?>

    
    <?php    
    else:?>

Login

username:


password:


register
    <?php endif; ?>

[/PHP]

logout.php:
[PHP]

<?php require("common.php"); unset($_SESSION['user']); header("Location: index.php"); echo ''; die("Redirecting to: index.php"); [/PHP]

First a couple of suggestions:

  1. I always put a configuration file (in your case common.php?) at the very top of the page and in a different directory(folder):

[php]<?php
/* This is how I do my configuration file, but yours would be a different name /
/
and a different folder. */
require_once ‘lib/includes/utilities.inc.php’;
?>
html>

TODO supply a title




TODO write content

[/php]

another thing to do is try to keep the PHP and HTML as separated as much as possible though sometimes this isn’t possible. I would also put your css back into the HTML instead of echoing out in PHP.

<link rel="stylesheet" href="lib/css/stylesheet.css">

You can always use a css preprocessor (Sass, Lass, etc…, I use Sass) if you want to save time writing CSS.

I would check into:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
instead of writing your own hashing / salting routine. It’s faster, securer and easier to do it this way in my opinion.

Just a suggestion but instead of checking if a user is online or offline with 1 or 0, why don’t you use the user’s information? I’ll show you what I mean…

I would put this in my configuration file that I put at the top of every php page:
[php]/* Use $user for sessions variable */
$user = isset($_SESSION[‘user’]) ? $_SESSION[‘user’] : NULL;[/php]

then when you read a user in, maybe do something like the following (I show you’ll a bit of my script):
[php] $db = DB::getInstance();
$pdo = $db->getConnection();
/* Setup the Query for reading in login data from database table */
$this->query = ‘SELECT id, username, password, security_level, first_name, last_name, email, home_phone, cell_phone, gender, birthday FROM users WHERE username=:username’;

    try {
        $this->stmt = $pdo->prepare($this->query); // Prepare the query:
        $this->stmt->execute([':username' => $data['username']]); // Execute the query with the supplied user's parameter(s):
    } catch (Exception $ex) {
        die("Failed to run query: " . $ex->getMessage()); // Do Not Use in Production Website - Log error or email error to admin:
    }

    $this->stmt->setFetchMode(PDO::FETCH_OBJ);
    $this->user = $this->stmt->fetch();

    if ($this->user) {
        $this->loginStatus = password_verify($data['password'], $this->user->password); // Check the user's entry to the stored password:
        unset($data['password'], $this->user->password); // Password(s) not needed then unset the password(s)!:
    } else {
        return FALSE;
    }

    if ($this->loginStatus) {
        $_SESSION['user'] = $this->user; // Set the session variable of user:
        return TRUE;
    } else {
        return FALSE;
    }[/php] 

Just ignore $this-> in the script when you see that mentally substitute it $, for example ($this->query, $query), for I am just showing how it could be done.

Then in a page you could do something like:

[php]if ($user && $user->security_level === ‘public’) {
/*

  • Sorry you don’t have access to this page
    */
    header(‘Location: index.php’);
    exit();
    } [/php]

in your case:
[php]if ($user) {
echo $user->username . " is online!
\n";
} else {
/* This is where you would write a script to determine who isn’t online */
}[/php]

If you want to get really fancy you could just write the username to a separate database table when that person is online and delete the username from table when he/she logs off, then have a script just check to see how is online or offline using PHP and maybe some JavaScript, Ajax and JSON?

Just some suggestions that you might or might not want to use. I find it simplier to put the user’s info (minus the password of course) into sessions. HTH John

or to delete (logoff) a user is very easy:
[php]function delete() {
unset($_SESSION[‘user’]);
$_SESSION[‘user’] = NULL;
return TRUE;
}[/php]

Op, to assume someone is going to log out is naive.

Sponsor our Newsletter | Privacy Policy | Terms of Service