Friday, March 2, 2012

Why dont you create your own CMS???--Part 8

From this post onwards,we are entering our second phase of our 'stupid' cms creation.
In this phase,we will
  • start using sessions.
  • create a simple user management system.
  • create some more useful functions .
  • build a small notification message system using 'freeow'.
We will be creating a session class and a user class to manage sessions and users respectively.So lets start our second phase...

Building the session class

This class will be used to create a session,set a session variable and get those session variables.
  • Open  stupid >>> include  directory.
  • create a file named  'session_class.php'.
  • Open the file in an editor and write the following code.

<?php
class Session {
 function Session() 
 {
  session_start();
 }
 
 function destroy_session()
 {
 session_unset();
 session_destroy();
 }
 
 function set_session($name,$val)
 {
  $_SESSION[$name] = $val;
 }
 
 function set_session_variable($name,$val)
 {
  $this->set_session($name,$val);
 }
 
 function get_session($name)
 {
  if(isset($_SESSION[$name]))
  return $_SESSION[$name];
 }
 
 function get_session_variable($name)
 { 
 return $this->get_session($name); 
 }
}

?> 

Since all the methods are simple , I am not elaborating each of them.
Now let us focus our attention on the user management system.

Building the user class

Our user class will have the following features
  • can check whether the user is loaded or not.
  • can check whether the user is logged in or not,active or not.
  • can insert a user when registered successfully.
  • can assign different levels for users.
  • can login and logout a user.
However you can increase the efficiency at any time by adding some more useful methods.
Before we move into the file,lets create a users table in our stupid database.
CREATE TABLE IF NOT EXISTS `users` (
            `u_id` smallint(11) NOT NULL AUTO_INCREMENT,
            `username` varchar(50) NOT NULL,
            `password` varchar(50) NOT NULL,
            `email` varchar(50) NOT NULL,
            `level` tinyint(11) NOT NULL DEFAULT '3',
            `active` tinyint(1) NOT NULL DEFAULT '1',
            PRIMARY KEY (`u_id`)
          ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;
The first registered user will be our admin.
Now lets code our user_class.php file.This will also be inside in our include directory.
So here is the code....

<?php

class User
{
    
    var $user_id;
    var $user_data = array();
    
    /**
     * Class Constructure
     * 
     * @param string $dbConn
     * @param array $settings
     * @return void
     */
    function __construct()
    {
        if (!empty($_SESSION['user_id'])) {
            $this->loadUser($_SESSION['user_id']);
        }
        
    }
    
    /**
     * Login function
     * @param string $uname
     * @param string $password
     * @param bool $loadUser
     * @return bool
     */
    
    function login($uname, $password, $loadUser = true)
    {
        global $db, $ss;
        $uname    = escape($uname);
        $password = $originalPassword = escape($password);
        $password = "MD5('$password')";
        $res      = $db->query("SELECT * FROM `users` 
  WHERE `username` = '$uname' AND `password` = $password LIMIT 1", __LINE__);
        if ($db->fetch_num($res) == 0)
            return false;
        if ($loadUser) {
            $this->user_data = $db->fetch_array($res);
            $this->user_id   = $this->user_data['u_id'];
            $ss->set_session_variable('user_id', $this->user_id);
            $ss->set_session_variable('username', $this->user_data['username']);
        }
        return true;
    }
    
    /**
     * Logout function
     * param string $redirectTo
     * @return bool
     */
    function logout($redirectTo = '')
    {
        global $ss;
        $ss->destroy_session();
        $this->userData = '';
        if ($redirectTo != '' && !headers_sent()) {
            header('Location: ' . $redirectTo);
            exit; //To ensure security
        }
    }
    /**
    to get a property of a user
    eg- 
    get_property('username') returns the username
    ***********************************/
    
    function get_property($property)
    {
        return $this->user_data[$property];
    }
    
    /**
     * Is the user an active user?
     * @return bool
     */
    function is_active()
    {
        return $this->user_data['active'];
    }
    
    /**
     * Is the user loaded?
     * @ return bool
     */
    function is_logged_in()
    {
        return empty($this->user_id) ? false : true;
    }
    
    function insertUser($data)
    {
        global $db;
        if (!is_array($data))
            echo ('Data is not an array');
        $password = "MD5('" . $data['password'] . "')";
        foreach ($data as $k => $v)
            $data[$k] = "'" . escape($v) . "'";
        $data['password'] = $password;
        $data_keys        = implode(',', array_keys($data));
        $data_values      = implode(',', $data);
        $db->query("INSERT INTO users (" . $data_keys . ") VALUES (" . $data_values . ")");
        return (int) mysql_insert_id($db->connection);
    }
    
    /**
     * A function that is used to load one user's data
     * @access private
     * @param string $userID
     * @return bool
     */
    function loadUser($user_id)
    {
        global $db, $ss;
        $res = $db->query("SELECT * FROM `users` WHERE `u_id` = '" . escape($user_id) . "' LIMIT 1");
        if (mysql_num_rows($res) == 0)
            return false;
        $this->user_data = mysql_fetch_array($res);
        $this->user_id   = $user_id;
        $ss->set_session_variable('user_id', $this->user_id);
        return true;
    }
    
}
?>
A brief idea of all the methods can be gained from reading the comments in the file itself.So I am skipping the description of this class file for time being.
if you have any doubts about the codes,please post comments....

0 comments:

Post a Comment