How to display login username throughout session?

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 5151 Views - Last Post: 18 November 2012 - 03:09 PM Rate Topic: -----

#1 kiasta  Icon User is offline

  • D.I.C Regular

Reputation: 20
  • View blog
  • Posts: 257
  • Joined: 18-November 07

How to display login username throughout session?

Posted 06 November 2012 - 11:28 AM

I've been trying to make it to where the username is displayed on the sidebar and control panel. I don't receive any errors, the username just will not be displayed. It should read "Welcome, $username", which it does upon the initial login, but as soon as I navigate from the page and come back or refresh the page the username will not be displayed it shows only "Welcome," and that's it. I even created a global variable to store the username but it still will not display after the initial login. I even went to the extreme to manually query the database for the username and store it to the global username everytime the page loads but it just will not work. If someone could point me in the right direction on a better way or what I'm doing wrong (obviously the query is bad practice and I have that there for testing purposes only).

index.php

<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>xxx</title>
        <!-- Stylesheet -->
        <link rel="stylesheet" type="text/css" href="xxx" />
        <!-- Javascript codes -->
        <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
        <script src="js/jquery.fullscreenr.js" type="text/javascript"></script>
        <script type="text/javascript">
            var FullscreenrOptions = {  width: 1920, height: 1080, bgID: '#bgimg' };
            jQuery.fn.fullscreenr(FullscreenrOptions);
        </script>
    </head>
    <body>
        <img id="bgimg" src="xxx"></img>
        <div id="realBody">
            <div id="container">
                <h1>DARKLOTUS GAMES</h1>
                    <?php
                    echo '<br><br><br><br><font color=white>';
                    $file = file_get_contents('xxx', true);
                    $content =  nl2br($file);
                    echo $content;
                    echo '</font>';
                    ?>
            </div>
            <div id="sidebar">
                <?php
                include 'user.inc.php';
                global $database;
                global $username;
                if(empty($_SESSION['user']))
                {
                    if (isset ($_POST['submit']))
                    {
                        $canLogin = $user -> login ($_POST);
                        if (!$canLogin)
                        {
                            $user->form('login');
                            echo '<h3>';
                            $user->display_notice('login');
                            echo '</h3>';
                            echo '</form></div></div>';
                        }
                        else if ($canLogin)
                        {
                            $query = "
                                    SELECT
                                        username
                                    FROM users
                                    WHERE
                                        username = :username
                            ";
                            $queryParams = array (
                                ':username' => $_POST['username']
                            );
                            try
                            {
                                $statement = $database -> prepare ($query);
                                $statement -> execute ($queryParams);
                            }
                            catch (PDOException $ex)
                            {
                                echo $ex -> getMessage ();
                                return false;
                            }
                            $row = $statement->fetch();
                            if ($row)
                            {
                                $username = $row['username'];
                            }
                            echo '<h1>Welcome, '.$username.'</h1><br>';
                            echo'<br>';
                            echo '<a href="user_cp.php"><img src="xxx" border="0" alt="Control Panel">Control Panel</a>';
                            echo '&nbsp;';
                            echo '<a href="user_cp.php?action=logout"><img src="xxx" border="0" alt="Logout">Logout</a>';
                            echo '</div></div>';
                            $user->redirect('index',0);
                        }
                    }
                    else
                    {
                        $user->form('login');
                    }
                }
                else if (!empty($_SESSION['user']))
                {
                    $query = "
                            SELECT
                                username
                            FROM users
                            WHERE
                                username = :username
                    ";
                    $queryParams = array (
                        ':username' => $_POST['username']
                    );
                    try
                    {
                        $statement = $database -> prepare ($query);
                        $statement -> execute ($queryParams);
                    }
                    catch (PDOException $ex)
                    {
                        echo $ex -> getMessage ();
                        return false;
                    }
                    $row = $statement->fetch();
                    if ($row)
                    {
                        $username = $row['username'];
                    }
                    echo '<h1>Welcome, '.$username.'</h1><br>';
                    echo'<br>';
                    echo '<a href="user_cp.php"><img src="xxx" border="0" alt="Control Panel">Control Panel</a>';
                    echo '&nbsp;';
                    echo '<a href="user_cp.php?action=logout"><img src="xxx" border="0" alt="Logout">Logout</a>';
                    echo '</div></div>';
                }
                ?>
            </div>
        </div>
    </body>
</html>


user.class.php

<?php

class User
{
    public $noticeCode;
    private $loginData;
    private $registerData;
    private $statement;

    public function set_array ($member, $element, $value)
    {
        switch ($member)
        {
            case 'loginData':
                {
                    if (property_exists ($this, 'loginData'))
                    {
                        $this -> loginData[$element] = $value;
                    }
                    else
                    {
                        echo "<br> Member does not exist";
                    }
                    break;
                }
            case 'registerData':
                {
                    if (property_exists ($this, 'registerData'))
                    {
                        $this -> registerData[$element] = $value;
                    }
                    else
                    {
                        echo "<br> Member does not exist";
                    }
                    break;
                }
        }
    }

    public function get_array ($member, $element)
    {
        switch ($member)
        {
            case 'loginData':
                {
                    if (isset ($this -> loginData[$element]))
                    {
                        return $this -> loginData[$element];
                    }
                    else
                    {
                        return NULL;
                    }
                    break;
                }
            case 'registerData':
                {
                    if (isset ($this -> registerData[$element]))
                    {
                        return $this -> registerData[$element];
                    }
                    else
                    {
                        return NULL;
                    }
                    break;
                }
        }
    }

    public function __construct ()
    {
        /* Prevent Javascript from readng SESSION cookies */
        ini_set ('session.cookie_httponly', true);
        /* Check if last session is from the same pc */
        if (!isset ($_SESSION['last_ip']))
        {
            $_SESSION['last_ip'] = $_SERVER['REMOTE_ADDR'];
        }
        if ($_SESSION['last_ip'] !== $_SERVER['REMOTE_ADDR'])
        {
            /* Clear the SESSION */
            $_SESSION = array ();
            /* Destroy the SESSION */
            session_unset ();
            session_destroy ();
        }
        require_once("user.inc.php");
        //Initialize member variables
        $this->noticeCode = array();
        $this->loginData = array();
        $this->registerData = array();
    }

    public function form($action)
    {
        global $username;
        switch($action)
        {
            case 'login':
            {
                echo '<h1>LOGIN</h1><br>';
                echo '<form name="login" action="index.php" method="post">';
                echo 'Username: <input type="text" name="username" /><br>';
                echo 'Password: <input type="password" name="password" /><br>';
                echo '<input type="submit" name = "submit" value="Login" />';
                break;
            }
            case 'register':
            {
                echo '<img id="bgimg" src="xxx"></img>';
                echo '<div id="realBody">';
                echo '<div id="register">';
                echo '<h1>REGISTER</h1><br>';
                echo '<form name="register" action="user_cp.php?action=register" method="post">';
                echo 'Username: <input type="text" name="username" value="xxx" /><br>';
                echo 'Password: <input type="password" name="password" value="xxx" /><br>';
                echo 'Verify Password: <input type="password" name="password2" value="xxx" /><br>';
                echo 'E-mail: <input type="text" name="email" value="xxx" /><br>';
                echo 'Verify E-mail: <input type="text" name="email2" value="xxx" /><br>';
                echo '<input type="submit" name = "submit" value="Register" />';

                break;
            }
            case 'registered':
            {
                echo '<img id="bgimg" src="xxx"></img>';
                echo '<div id="realBody">';
                echo '<div id="logout">';
                echo '<h1>REGISTERED</h1><br>';
                echo '<br><br>Registration Successful!';
                break;
            }
            case 'logout':
            {
                echo '<img id="bgimg" src="xxx"></img>';
                echo '<div id="realBody">';
                echo '<div id="logout">';
                echo '<h1>LOGOUT</h1><br>';
                echo '<h3>';
                echo '<br><br>Logout Successful!';
                echo '</h3>';
                break;
            }
        }
    }

    public function display_notice($action)
    {
        echo "<h3>";
        if ($action != 'manual')
        {
            foreach ($this -> noticeCode as $element => $value)
            {
                if (!empty ($value))
                {
                    switch($action)
                    {
                        case 'login': new Message($value); break;
                        case 'register': new Message($value); break;
                    }
                }
            }
        }
        else if ($action == 'manual')
        {
            new Message ($this->noticeCode['manual']);
        }
        echo '</h3>';
    }

    public function redirect($action, $wait)
    {
        switch($action)
        {
            case 'login': echo '<meta http-equiv="refresh" content="'.$wait.';url=index.php?action='.$action.'">'; break;
            case 'user_cp': echo '<meta http-equiv="refresh" content="'.$wait.';url=user_cp.php">'; break;
            case 'index': echo '<meta http-equiv="refresh" content="'.$wait.';url=index.php">'; break;
            case 'register': echo '<meta http-equiv="refresh" content="'.$wait.';url=user_cp.php?action='.$action.'">'; break;
            case 'logout': echo '<meta http-equiv="refresh" content="'.$wait.';url=user_cp.php?action='.$action.'">'; break;
        }
    }

    public function user_cp()
    {
        echo '<body>';
        echo '<img id="bgimg" src="xxx"></img>';
        echo '<div id="realBody">';
        echo '<div id="user-cp">';
        echo '<h1>Control Panel</h1><br>';
        echo '<a href="index.php"><img src="xxx" border="0" alt="Home">Home</a>';
        echo '&nbsp;';
        echo '<a href="user_cp.php?action=logout"><img src="xxx" border="0" alt="Logout">Logout</a>';
        echo '</div></div>';
    }

    private function salt()
    {
        $this->loginData['salt'] = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
        for ($round = 0; $round < 65536; $round++)
        {
            $this->loginData['salt'] = hash('sha512', $this->loginData['salt']);
        }
    }

    private function hash($action)
    {
        switch($action)
        {
            case 'login':
            {
                for ($round = 0; $round < 65536; $round++)
                {
                    $this->loginData['hash'] = hash('sha512', $this->loginData['password'] . $this->loginData['salt']);
                }
                break;
            }
            case 'register':
            {
                $this->salt();
                for ($round = 0; $round < 65536; $round++)
                {
                    $this->registerData['hash'] = hash('sha512', $this->registerData['password'] . $this->registerData['salt']);
                }
                break;
            }
        }
    }

    private function validate($action)
    {
        global $database;
        switch($action)
        {
            case 'login':
            {
                $query = "
                        SELECT
                            id,
                            username,
                            password,
                            salt,
                            email
                        FROM users
                        WHERE
                            username = :username
                ";
                $queryParams = array (
                    ':username' => $this->loginData['username']
                );
                try
                {
                    $this -> statement = $database -> prepare ($query);
                    $this -> statement -> execute ($queryParams);
                }
                catch (PDOException $ex)
                {
                    echo $ex -> getMessage ();
                    $this -> noticeCode['login'] = LOGIN_FAILED;
                    return false;
                }
                $row = $this->statement->fetch();
                if ($row)
                {
                    return $row;
                }
                else
                {
                    return false;
                }
                break;
            }
            case 'register':
            {
               /******************************************
                * CHECK IF CREDENTIALS FOLLOW GUIDELINES *
                ******************************************/
                //CHECK EMAIL
                if(!filter_var($this->registerData['email'], FILTER_VALIDATE_EMAIL))
                {
                    $this -> noticeCode['email'] = INV_EMAIL;
                }
                //CHECK USERNAME
                $count = mb_strlen ($this->registerData['username'], 'UTF-8');
                if (!ctype_alnum ($this->registerData['username']))
                {
                    $this -> noticeCode['username'] = INV_USER;
                }
                else if ($count < 4)
                {
                    $this -> noticeCode['username'] = SHORT_USER;
                }
                else if ($count > 15)
                {
                    $this -> noticeCode['username'] = LONG_USER;
                }
                //CHECK PASSWORD
                $count = mb_strlen ($this->registerData['password'], 'UTF-8');
                if ($count < 6)
                {
                    $this -> noticeCode['password'] = SHORT_PASS;
                }
                else if ($count > 30)
                {
                    $this -> noticeCode['password'] = LONG_PASS;
                }
                if (!empty ($this -> noticeCode))
                {
                    return false;
                }

               /****************************************************
                * VERIFY USERNAME WITH DATABASE, UNIQUE USERS ONLY *
                ****************************************************/

                $query = "
                    SELECT
                        1
                    FROM users
                    WHERE
                        username = :username
                ";

                $query_params = array(
                    ':username' => $this->registerData['username']
                );

                try
                {
                    $this -> statement = $database->prepare($query);
                    $this -> statement->execute($query_params);
                }
                catch(PDOException $ex)
                {
                    echo $ex -> getMessage ();
                    $this -> noticeCode['register'] = REG_FAILED;
                    return false;
                }

                $row = $this->statement->fetch();

                if($row)
                {
                    $this -> noticeCode['username'] = EXISTS_USER;
                    return false;
                }

               /**************************************************
                * VERIFY EMAIL WITH DATABASE, UNIQUE EMAILS ONLY *
                **************************************************/

                $query = "
                    SELECT
                        1
                    FROM users
                    WHERE
                        email = :email
                ";

                $query_params = array(
                    ':email' => $this->registerData['email']
                );

                try
                {
                    $this -> statement = $database->prepare($query);
                    $this -> statement->execute($query_params);
                }
                catch(PDOException $ex)
                {
                    echo $ex -> getMessage ();
                    $this -> noticeCode['register'] = REG_FAILED;
                    return $regSuccess;
                }
                $row = $this->statement->fetch();

                if($row)
                {
                    $this -> noticeCode['email'] = EXIST_EMAIL;
                    return false;
                }
                if (empty ($this->noticeCode))
                {
                    return true;
                }
                else
                {
                    return false;
                }
                break;
            }
        }
    }

    public function login ($post)
    {
        global $database;
        global $username;
        if (!empty ($post))
        {
            foreach ($post as $element => $value)
            {
                if ($element != 'submit')
                {
                    $this -> loginData[$element] = $value;
                }
            }
            if (!empty ($this -> loginData['username']) && !empty ($this -> loginData['password']))
            {
                $loginOK                     = false;
                $row                         = $this -> validate('login');
                if ($row)
                {
                    $this->loginData['salt'] = $row['salt'];
                    $this->hash('login');

                    if ($this->loginData['hash'] === $row['password'])
                    {
                        $loginOK = true;
                        //for displaying username after logged in
                        $username = $row['username'];
                    }
                    else
                    {
                        $this->noticeCode['login'] = LOGIN_FAILED;
                    }
                }
                if ($loginOK)
                {
                    unset ($row['salt']);
                    unset ($row['password']);
                    $_SESSION['user'] = $row;
                    $this -> noticeCode['login'] = LOGIN_SUCCESS;
                    return true;
                }
            }
            else
            {
                $this -> noticeCode['login'] = EMPTY_FIELD;
                return false;
            }
        }
    }

    public function register ($post)
    {
        global $database;
        $regSuccess = false;
        if (!empty ($post))
        {
            foreach ($post as $element => $value)
            {
                if ($element != 'submit')
                {
                    $this -> registerData[$element] = $value;
                }
            }

           /**************************************
            * CHECK IF PASSWORD AND EMAILS MATCH *
            **************************************/

            if ($this -> registerData['password'] == $this -> registerData['password2'] && $this -> registerData['email'] ==
                    $this -> registerData['email2'])
            {
                /*DETERMINES IF USER CAN REGISTER DATA ENTERED*/
                $canRegister = $this->  validate('register');

               /************************************************************
                * INSERT DATA TO DATABASE, USING PDO STRUCTURED STATEMENTS *
                ************************************************************/
                if ($canRegister)
                {
                    $query = "
                        INSERT INTO users (
                            username,
                            password,
                            salt,
                            email
                        ) VALUES (
                            :username,
                            :password,
                            :salt,
                            :email
                        )
                    ";
                    /*GENERATE PASSWORD HASH AND ASSIGN VALUE TO "registerData" ARRAY*/
                    $this->hash('register');
                    $query_params = array(
                            ':username' => $this->registerData['username'],
                            ':password' => $this->registerData['hash'],
                            ':salt' => $this->registerData['salt'],
                            ':email' => $this->registerData['email']
                    );
                    try
                    {
                        $this->statement = $database->prepare($query);
                        $this->statement->execute($query_params);
                    }
                    catch(PDOException $ex)
                    {
                        echo $ex -> getMessage ();
                        $this -> noticeCode['register'] = REG_FAILED;
                        return $regSuccess;
                    }
                    $regSuccess = true;
                    $this -> noticeCode['register'] = REG_SUCCESS;
                    return $regSuccess;
                }
                else
                {
                    return $regSuccess;
                }
            }
            else
            {
                if ($this -> registerData['password'] != $this -> registerData['password2'])
                {
                    $this -> noticeCode['password'] = MATCH_PASS;
                }
                if ($this -> registerData['email'] != $this -> registerData['email2'])
                {
                    $this -> noticeCode['email'] = MATCH_EMAIL;
                }
                return $regSuccess;
            }
        }
        else
        {
            $this -> noticeCode['register'] = EMPTY_FIELD;
            return $regSuccess;
        }
    }
}

?>



user.inc.php

<?php
//Includes
require_once("database.class.php");
require_once("user.class.php");
require_once("message.class.php");
//Start an instance of the Database Class
$database = new Database();
$database = $database -> db_connect();
//Create an instance of the User Class
$user     = new User();
$username = '';
//Because I have only php 5.3 I have the godawful magic quotes
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
    function undo_magic_quotes_gpc(&$array)
    {
        foreach($array as &$value)
        {
            if(is_array($value))
            {
                undo_magic_quotes_gpc($value);
            }
            else
            {
                $value = stripslashes($value);
            }
        }
    }

    undo_magic_quotes_gpc($_POST);
    undo_magic_quotes_gpc($_GET);
    undo_magic_quotes_gpc($_COOKIE);
}
session_start();

?>


database.class.php

<?php

session_start();

class Database
{

    private $dbConnect;
    var $dbUser = "xxx";
    var $dbPass = "xxx";
    var $DSN    = "mysql:host=xxx;dbname=xxx;charset=utf8";
    var $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );

    public function __construct ()
    {
        try
        {
            $this -> dbConnect = new PDO ($this -> DSN, $this -> dbUser, $this -> dbPass, $options);
        }
        catch (PDOException $ex)
        {
            die ("Failed to connect to the database: " . $ex -> getMessage ());
        }
        /*$this -> dbConnect -> setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this -> dbConnect -> setAttribute (PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);*/
    }
    public function db_connect ()
    {
        return $this -> dbConnect;
    }

}

?>



style.css

body {
    overflow:hidden; 		/* needed to eliminate scrollbars caused by the background image */
    padding:0;margin:0;		/* necesarry for the raster to fill the screen */
    /*height:100%;width:100%;*/
}

#bgimg {
    position:absolute;
    z-index: -1;
}

#realBody {
    position:absolute;
    z-index: 5;
    overflow:auto;
    height:100%;width:100%;
    background: url('xxx');
}

#container {
    position: absolute;
    width: 800px;
    /*height: 640px;*/
    margin-left: 5%;
    margin-top: 2%;
    padding-top: 8px;
    padding-bottom: 15px;
    padding-left: 15px;
    padding-right: 15px;
    border-radius: 15px;
    background:rgba(0,0,0,.9);
    font-family: 'space_age', sans-serif;
    font-size: 20px;
}

#container h1 {
    color:#fff;
    font-family: 'space_age', sans-serif;
    font-size:48px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#container form {
    color:#fff;
    font-family: 'space_age', sans-serif;
    font-size:14px;
    font-weight: normal;
    padding-right: 28px;
    text-decoration:none;
    text-align:right;
}

#sidebar {
    position: absolute;
    width: 320px;
    height: 215px;
    margin-left: 64%;
    margin-top: 2%;
    padding-top: 8px;
    padding-bottom: 15px;
    padding-left: 15px;
    padding-right: 15px;
    border-radius: 15px;
    background:rgba(0,0,0,.9);

}

#sidebar h1 {
    color:#fff;
    font-family: 'space_age', sans-serif;
    font-size:28px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#sidebar h3 {
    color:red;
    font-family: verdana;
    font-size:10px;
    padding-left: 25px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#sidebar form {
    color:#fff;
    font-family: verdana;
    font-size:14px;
    font-weight: normal;
    padding-right: 28px;
    text-decoration:none;
    text-align:right;
}

#logout {
    width: 320px;
    height: 215px;
    margin: auto;
    margin-top: 150px;
    padding-top: 8px;
    padding-bottom: 15px;
    padding-left: 15px;
    padding-right: 15px;
    border-radius: 15px;
    background:rgba(0,0,0,.9);

}

#logout h1 {
    color:#fff;
    font-family: 'space_age', sans-serif;
    font-size:28px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#logout h3 {
    color:red;
    font-family: verdana;
    font-size:10px;
    padding-left: 25px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#register {
    width: 400px;
    height: 300px;
    margin: auto;
    margin-top: 150px;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-left: 15px;
    padding-right: 15px;
    border-radius: 15px;
    background:rgba(0,0,0,.9);

}

#register h1 {
    color:#fff;
    font-family: 'space_age', sans-serif;
    font-size:30px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#register h3 {
    color:red;
    font-family: verdana;
    font-size:10px;
    padding-left: 25px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#register form {
    color:#fff;
    font-family: verdana;
    font-size:14px;
    font-weight: normal;
    padding-right: 32px;
    text-decoration:none;
    text-align:right;
}

#user-cp {
    width: 800px;
    height: 640px;
    margin: auto;
    margin-top: 40px;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-left: 15px;
    padding-right: 15px;
    border-radius: 15px;
    background:rgba(0,0,0,.9);

}

#user-cp h1 {
    color:#fff;
    font-family: 'space_age', sans-serif;
    font-size:34px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

#user-cp h3 {
    color:red;
    font-family: verdana;
    font-size:10px;
    padding-left: 25px;
    font-weight: normal;
    text-decoration:none;
    text-align:center;
}

@font-face {
    font-family: space_age;
    src: url('xxx');
}


I believe I've given all relevant code; if you need more just let me know. Thanks again for all your guys' help thusfar, it is very much appreciated!

Also, I have been working on optimizing my code, but for now I'm just trying to get everything working the way it should so it's a bit of a mess, sorry for the eyesore haha.

This post has been edited by kiasta: 06 November 2012 - 11:32 AM


Is This A Good Question/Topic? 0
  • +

Replies To: How to display login username throughout session?

#2 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: How to display login username throughout session?

Posted 06 November 2012 - 11:48 AM

Hello,

Firstly, could you explain what you hope to achieve with this bit of your code?
/* Check if last session is from the same pc */
        if (!isset ($_SESSION['last_ip']))
        {
            $_SESSION['last_ip'] = $_SERVER['REMOTE_ADDR'];
        }
        if ($_SESSION['last_ip'] !== $_SERVER['REMOTE_ADDR'])
        {
            /* Clear the SESSION */
            $_SESSION = array ();
            /* Destroy the SESSION */
            session_unset ();
            session_destroy ();
        }


A session will not span over multiple IP addresses, so this check seems pointless. If you go onto another machine you will get a new session, regardless of what account you log into. If you want to check if they use a different PC, you will need to log their IP in the database with their user details.

Instead of calling the username from the database every time the page loads, store it in the session when they successfully login. Then access it from that value. A simple text-string in a session is not as expensive as database calls on every page load.

As far as your bug goes, I would suggest implementing my above idea and seeing if it goes away, without some proper debugging I can't say for sure where the issue lies, however your code is quite untidy.

Another suggestion would be to keep your code more separate. The login/authentication logic should not be mangled in with your HTML output code, it should be away from that.
Was This Post Helpful? 1
  • +
  • -

#3 kiasta  Icon User is offline

  • D.I.C Regular

Reputation: 20
  • View blog
  • Posts: 257
  • Joined: 18-November 07

Re: How to display login username throughout session?

Posted 06 November 2012 - 12:11 PM

I'm still new to php, so I've really just been trying to learn as I go. As for that bit of code I read some tutorial about session hijacking and that was one of the measures they used. And as far as the query goes I actually only put the query there to see if it would display the username but it still didn't. Using $_SESSION worked like a charm, I can't believe I didn't think of that.

When you say "Another suggestion would be to keep your code more separate. The login/authentication logic should not be mangled in with your HTML output code, it should be away from that." what do you mean exactly, to not use echo to echo out html? Or to not use html forms? Also as far as structuring goes do you have any suggestions on a standardized structure I should follow because I'm learning all of this in my freetime and I'm trying to learn it all properly. Thansk for the advice!

This post has been edited by Dormilich: 15 November 2012 - 01:06 AM
Reason for edit:: removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

#4 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: How to display login username throughout session?

Posted 06 November 2012 - 12:19 PM

Hello again,

Your code just seems too, close quarters for my own liking. Personally my applications tend to follow the following layout...

www - This folder contains every public-facing file the users will access. Each file has merely a few lines of code, the first including a framework library from 'lib' (see below) and another few constructing a module and outputting it (see modules below).

modules - This is where the logic and calculations are run for each page. Each module takes care of anything that might happen on said page, dealing with requests and such posted to that page. Each module will begin processing when it's constructed and needs to provide some form of output when called as a string (__toString()).

templates - These are mostly HTML layouts which are loaded by the modules, they can call any variables the modules previously set for them as though the template is an object with them set. All templates must have a fall-back if the module for some reason failed to set anything or if they are called by the wrong module.

lib - This directory contains libraries (the framework one being the most important). Each library is a static class which contains functions, nothing else. Each class is responsible for a certain type of function. An example class would be UserHandler, this has a large array of functions relating to users. The framework library is generally the only one not a class, this has some global functions and is in charge of loading the libraries needed as and when they are, as well as constructed database/memcached/ldap connections and such.

Further reading on such things: http://oreilly.com/p.../mvc-intro.html
Was This Post Helpful? 1
  • +
  • -

#5 kiasta  Icon User is offline

  • D.I.C Regular

Reputation: 20
  • View blog
  • Posts: 257
  • Joined: 18-November 07

Re: How to display login username throughout session?

Posted 06 November 2012 - 12:46 PM

Thank you, I shall give that a read.

This post has been edited by Dormilich: 15 November 2012 - 01:07 AM

Was This Post Helpful? 0
  • +
  • -

#6 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1252
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: How to display login username throughout session?

Posted 06 November 2012 - 03:45 PM

Why not just use an MVC framework and not waste time building yet another MVC framework? I use CakePHP and it's really simple and fast to get started.
Was This Post Helpful? 1
  • +
  • -

#7 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: How to display login username throughout session?

Posted 06 November 2012 - 03:52 PM

View PostSergio Tapia, on 06 November 2012 - 10:45 PM, said:

Why not just use an MVC framework and not waste time building yet another MVC framework? I use CakePHP and it's really simple and fast to get started.


I don't use pre-made frameworks or libraries (jQuery is as far as I'll go) because it's my personal preference not to. I hate off the shelf solutions and I feel making them myself gives me a greater understanding of how said thing works and betters my experience as a programmer.

If I was to just bundle pre-made things together there is nothing separating me from the other developers that I work around, where as having built all of my applications from the ground up including their frameworks and libraries means that I have the edge.

Not only can I adapt my solutions without having to rummage around other peoples documentations (or code if they lack that), I also have no unneeded overheads included as I can easily adapt said frameworks/libraries to fit the requirements of the application in hand.

This post has been edited by Kruithne: 06 November 2012 - 03:53 PM

Was This Post Helpful? 0
  • +
  • -

#8 kiasta  Icon User is offline

  • D.I.C Regular

Reputation: 20
  • View blog
  • Posts: 257
  • Joined: 18-November 07

Re: How to display login username throughout session?

Posted 06 November 2012 - 10:48 PM

This is exactly why I'm not just taking a shortcut like using openID or Facebook Login: OAuth. I am doing this to learn and to eventually build a series of web-based games. I am doing this solo and will need to learn lots of new things that I've not had time for until recently (due to 65 hour work weeks being an IT Manager). I have all this free time and can finally dedicate some time on realizing my passion. I want to do everything from scratch so I will have the knowledge and experience. I find programming to be quite fun (very frustrating at times, though) so this is a hobby going to turn into a profession for me. I'm not going to give up and I've been through college 4 times but it's just not for me. I expect that it will take years to become experienced and knowledgeable enough to develop professional games. For now I am trying to learn everything the right way so I won't have any hiccups along the road.

I'm going to be studying MVC for the better part of the night, thanks again Kruithne for the info and the help.

As for using CakePHP I will look into it, it might give me some ideas; thanks Sergio.

This post has been edited by Dormilich: 15 November 2012 - 01:07 AM
Reason for edit:: removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

#9 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: How to display login username throughout session?

Posted 07 November 2012 - 02:15 AM

You're welcome, I am happy to see someone starting out in programming has taken that view on things such as OpenID. Normally I would expect people to jump at is a a portal away from having to deal with various API's such as Facebook for integration of cross-site log-ins. Personally I think sites should have their own authentication systems, it allows people who need it to stay anonymous rather than having everything linked to one account, it's also never a good idea to rely on another site when you can help it, even the bigger sites.

Good luck with your adventures into the world of programming, DreamInCode is here to help you.

This post has been edited by Dormilich: 15 November 2012 - 01:08 AM
Reason for edit:: removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

#10 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3712
  • View blog
  • Posts: 5,964
  • Joined: 08-June 10

Re: How to display login username throughout session?

Posted 07 November 2012 - 01:03 PM

View PostKruithne, on 06 November 2012 - 10:52 PM, said:

If I was to just bundle pre-made things together there is nothing separating me from the other developers that I work around, where as having built all of my applications from the ground up including their frameworks and libraries means that I have the edge.

Consider it from the perspective of somebody leading a larger project, with perhaps a handful of developers working on it. Or somebody who may want to reserve the possibility of hiring somebody else to expand on your work in the future. Who will be the greater asset: the developer who has experience using existing frameworks and building on code written by others, or the developer who's experience is mostly using his own code?

While I completely understand the educational value of building your own framework (I've done that myself countless times), the edge you are talking about there only really exists in this way for relatively small, solo projects, and it will disappear as soon as you are no longer the only developer working on it.

Frameworks like CakePHP, ZF or Symfony have excellent documentation. For teams, that is necessary.
Was This Post Helpful? 2
  • +
  • -

#11 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1252
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: How to display login username throughout session?

Posted 07 November 2012 - 01:08 PM

Uh-huh. Nail on the head.

Using a baseline framework lets developer work together. If you have the time and are flying solo, by all means I agree: Write your own. It's a fantastic way to learn.

Otherwise, just use a framework and get down to business.
Was This Post Helpful? 0
  • +
  • -

#12 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: How to display login username throughout session?

Posted 08 November 2012 - 05:39 AM

While on most parts I do agree that when working as a team pulling out a framework that all the developers are familiar with is great for saving time and allows all the developers to understand the underlying system properly, I would partly disagree.

It's nothing but personal preference, really, but I find even when working with other developers (which I do, often), when we sit down for a short period of time and bash out a framework we are all happy with and has the functionality we need to achieve our end goal, it works better than using an out of the box solution.

Of course, it all depends on the work environment you are working under. Most of the time the managers are happy enough to allow extra time for building a framework, which rarely takes any time at all as nine times out of ten you don't require all of the functionality that one would bring.

I'm not trying to disprove any points here, just stating that from my personal experience things go down better when the project has it's own framework developed, which is obviously not viable if you are in a tight development cycle.
Was This Post Helpful? 0
  • +
  • -

#13 kiasta  Icon User is offline

  • D.I.C Regular

Reputation: 20
  • View blog
  • Posts: 257
  • Joined: 18-November 07

Re: How to display login username throughout session?

Posted 14 November 2012 - 04:48 PM

So, before I pull my hair out, where did you guys learn about the complexities of MVC? Perhaps I'm just not skilled enough yet to learn it. It doesn't make sense to me. I understand the necessity of breaking down code into parts to make it more accessible and scalar, but MVC's logic doesn't make sense to me. I read the descriptions to Model, View, Controller and it's all greek to me (and I can understand greek!), now if they explained it with simple code instead of a completed framework, I could understand it.

Maybe I just need more experience, more skill. I don't know, but it's all just overwhelming. I think I'll just continue to do things how I've been doing them and slowly implement different ideas instead of drastically altering the way I program. Perhaps I should have learned a better way of programming so I wouldn't be in this situation to begin with. Anyways I thank you all for your help and advice but I simply am not yet ready for MVC, apparently.
Was This Post Helpful? 0
  • +
  • -

#14 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3712
  • View blog
  • Posts: 5,964
  • Joined: 08-June 10

Re: How to display login username throughout session?

Posted 14 November 2012 - 05:57 PM

The basic structure of MVC isn't all that complex, really. If you just look at it through the code of a complex framework like CakePHP, ZF or Symfony, it won't be easy to follow, but it doesn't have to be set up in that manner. It can be done in a much simpler, and more limiting, way.

The MVC pattern just describes a system that is split into three parts:

  • The business logic (Controllers), which decides how the application reacts to requests made to specifics parts of the application. So if a user calls the "addEntry" action of a the "blog" part of the site, the controller code for that part of the site will be called to decide what database interaction is needed and what output needs to be shown.

  • The database interaction (Models), which provides functions that do specific tasks on the database. So in the above "blog/addEntry" scenario, the controller would call a function provided by the model, something like addBlogEntry($title, $text), which would then add the provided entry data into the database.

  • The presentation (Views), which provides code to generate the output needed for specific parts of the application. Again, using the above "blog/addEntry" scenario, it would provide separate functions/classes/files to create HTML pages that would show a "success" page, or a "error" page, or show the "addEntry" HTML form again, based on what the Controller decides it needs to show.


This doesn't have to involve complex classes or such. (Although if you know how to use classes, it tends to makes more sense to use them than to not use them.) - As an example, I'll show you how the above scenario could be accomplished using a few simple functions.

Spoiler


The above is a perfectly valid MVC system, even though it avoids using objects completely, relying more on functions and basic include strategies. Hopefully that'll make the MVC pattern easier to spot :)
Was This Post Helpful? 1
  • +
  • -

#15 kiasta  Icon User is offline

  • D.I.C Regular

Reputation: 20
  • View blog
  • Posts: 257
  • Joined: 18-November 07

Re: How to display login username throughout session?

Posted 14 November 2012 - 08:56 PM

See now this actually makes sense to me. I've been trying to learn MVC by studying different frameworks (primarily cakePHP) and it just seemed a little much, especially their advanced techniques that I've yet to understand; I'm still struggling with polymorphism, class inheritance and PDO.

If you don't mind I just have a couple of questions:

1.) Is the View allowed access the Model at any point?

2.) When creating classes is it necessary to create a base class for all classes to extend from or just a base class for each: Model, View, and Controller?

3.) If question 2 is true, how will I know what is required in a base class? (this one has been bugging me for a while since I started learning MVC)


The reason for my first question is I found a simple tutorial here and they show the view accessing the model directly, which contradicts this diagram I found in another tutorial (though I don't remember the link). I've also read other tutorials with contradicting practices, which was a bit frustrating and confusing to learn this.

The second question spawned from the O'reily tutorial where he explains that a base class must be made, but doesn't go into detail on what is required of a base class (in his example). I know it would be more efficient to use proper class inheritance (I believe is what they are called) but I just don't really know what a class absolutely needs for it to be a class (in regards to MVC).

As you can tell I've been doing a lot of research on this subject; I just couldn't find a simple basic explanation explaining the base logic, like you've given. I really appreciate your clarification, I think I can make sense of it now with some practice.

*EDIT* Forgot to add this link, his argument to why the model should be accessed directly by the view: LINK

This post has been edited by Dormilich: 15 November 2012 - 02:56 AM
Reason for edit:: removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2