Simple Authentication + "Last Visited"

By Suhana on Dec 09, 2009

Just a simple proof-of-concept script showing the basic login / logout process.
Added the register_user() function and fixed a small syntax error.

<?php

/**
 *  Copyright (C) 2009, Suhana
 *  All rights reserved.
 *  
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of the copyright holder nor the
 *     names of their contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *  
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY
 *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
 *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Revision History
 *
 * 0.2 Fri 11 Dec 2009
 *     Added register_user(), SQL table definition and fixed a syntax error
 *     in show_last_visit.
 *
 * 0.1 Wed 09 Dec 2009
 *     Initial Revision
 */

/**
 * Table (Users) Definition:
 *  
 *      ID        <INTEGER>
 *      Username  <STRING>
 *      Password  <STRING>
 *      LastVisit <INTEGER>
 *  
 *  Assumptions:
 *  
 *      a) The database connection has already been opened (mysql)
 *      b) Sessions have been started
 *  
 *  Caveats:
 *  
 *      Pretty basic stuff here - You need to provide the relevant login form,
 *      links to logout, and whatever else the site may need.
 *      
 *      **** UNTESTED ****
 */

/**
 * SQL to create the table (You can paste this into a phpMyAdmin SQL window)
 *

    --
    -- Table structure for table `Users`
    --

    CREATE TABLE IF NOT EXISTS `Users`
    (
        `ID`        INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
        `Username`  VARCHAR(15) NOT NULL,
        `Password`  CHAR(32) NOT NULL,
        `LastVisit` INT(10) UNSIGNED NOT NULL DEFAULT '0',

        PRIMARY KEY          (`ID`),
        UNIQUE  KEY `ByName` (`Username`)
    )
    ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

    --
    -- End
    --

 *
 */

/**
 * Returns TRUE if the supplied credentials are valid. Also logs the user in
 * and updates the LastVisit value.
 */
function login( $username, $password )
{
    // cleanup the input

    $username = mysql_real_escape_string($username);
    $password = md5($password);

    // try and find the relevant user

    $sql = "SELECT ID, LastVisit FROM Users WHERE ((Username = '$username') AND (Password = '$password'))";
    $rs  = mysql_query($sql);

    // error check

    if (!$rs)
        die(mysql_error());

    // actually grab the row itself ...

    $row = mysql_fetch_assoc($rs);

    // ... and free the result set

    mysql_free_result($rs);

    // make sure we've actually found somebody

    if (!$row)
        return false;

    // woohoo! now popuplate the session variables ...

    $_SESSION['UserID']    = $row['ID'];
    $_SESSION['LastVisit'] = $row['LastVisit'];

    // ... and update the time this user logged in

    $sql = "UPDATE Users SET LastVisit = " . time() . " WHERE ID = " . $row['ID'];

    // again, quick error check (just in case)

    if (!mysql_query($sql))
        die(mysql_error());

    // and return

    return true;
}

/**
 * Logs the user out of the current session
 */
function logout( )
{
    // just clear the variables

    $_SESSION['UserID']    = 0;
    $_SESSION['LastVisit'] = 0;
}

/**
 * Returns TRUE if the user is currently logged in
 */
function is_logged_in( )
{
    // idiot check

    if (!isset($_SESSION['UserID']))
        return false;

    // okay, but it might be 0 (after a logout ...)

    if ($_SESSION['UserID'] == 0)
        return false;

    // woohoo!

    return true;
}

/**
 * Retrieves the current user id (or 0 if not logged in)
 */
function get_user_id( )
{
    // idiot check

    if (!is_logged_in())
        return 0;

    // return the important bit

    return $_SESSION['UserID'];
}

/**
 * Retrieves the last time the user logged in (or 0 if not/never logged in)
 */
function get_last_visit( )
{
    // idiot check

    if (!is_logged_in())
        return 0;

    // return the important bit

    return $_SESSION['LastVisit'];
}

/**
 * Displays "Last Visit: ...", the last time the user successfully logged in.
 */
function show_last_vist( )
{
    if (!is_logged_in())
        return;

    echo "Last Visit: ";

    $last_vist = get_last_visit();

    if (!$last_vist)
    {
        // oo - we've never logged in before

        echo "Never";
    }
    else
    {
        // format here, rather than at SQL level thus keeping display logic
        // separate from the back-end.

        echo date("Ymd His", $last_visit); 
    }
}

/**
 * Registers a new user account, return TRUE on success, FALSE if the
 * username already exists.
 */
function register_user( $username, $password )
{
    // again, cleanup the variables

    $username = mysql_real_escape_string($username);
    $password = md5($password);

    // and insert the data

    $sql  = "INSERT INTO Users (ID, Username, Password, LastVisit) ";
    $sql .= "VALUES (NULL, '" . $username . "', '" . $password . "', 0)",

    // We use NULL int THE ID field which has the auto-increment attribute
    // to safely generate the next ID #.

    // Notice, we specify exactly what fields are being inserted into (always
    // good practice)

    if (!mysql_query($sql))
    {
        if (mysql_errno() == 1062)
        {
            // oops - looks like the username already exists!

            return false;
        }

        // no idea what went on here ...

        die(mysql_error());
    }

    return true;
}

Comments

Sign in to comment.
Suhana   -  Dec 11, 2009

Added register_user() as suggested, fixed a small syntax error -- missing { in show_last_vist() -- and added the SQL needed to create the table in phpMyAdmin or at the MySQL command prompt.

 Respond  
Genesis2001   -  Dec 09, 2009

Agreed Neptune. However, it should be wrapped in a class and the database control should be controlled by a master object for quick use. (phpBB3 DBAL, anyone? :P)

 Respond  
^Neptune   -  Dec 09, 2009

I really, really like this. It includes simple comments throughout the code so I can understand it perfectly, and as a set of functions this is very easy to incorporate into any script.

Now all we need is a register_user() methinks. :P

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.