Return to Snippet

Revision: 4815
at January 22, 2008 00:17 by ecavazos


Initial Code
<?php
// start session
session_start();
if (array_key_exists('username', $_SESSION)) {
    // user already authenticated
    header('location: index.php');
}

if ($_POST) {
    
    if (array_key_exists('username', $_POST)) {
        require_once('codes/dal.php');
        $dal = new DataAccessLayer();

        $user =  trim($_POST['username']);
        $pass = trim($_POST['password']);
        $pass = bin2hex(md5($pass, TRUE ));
        
        // join the 'users' and 'roles' tables
        $sql = 'select '
             . 'u.id '
             . ',u.username '
             . ',u.password '
             . ',u.role_id '
             . ',r.name '
             . ',u.full_name '
             . ',u.email '
             . ',u.description '
             . 'from users as u '
             . 'join roles as r on u.role_id = r.id '
             . 'where u.username = \'' . $user . '\'';
        
        $result = $dal->query($sql);
        
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            if ($pass == $row['password']) {
                // create session variables
                $_SESSION['user_id'] = $row['id'];
                $_SESSION['username'] = $row['username'];
                $_SESSION['full_name'] = $row['full_name'];
                $_SESSION['role_id'] = $row['role_id'];
                $_SESSION['role_name'] = $row['name'];
                $_SESSION['email'] = $row['email'];
                $_SESSION['password'] = $row['password'];
                
                // check if password is default
                if($pass == bin2hex(md5('pass', TRUE ))) {
                    $_SESSION['default'] = true;
                    // login successful - but password needs to be changed
                    header('location: users/change_password.php');
                } else {
                    // login successful - redirect to home page
                    header('location: index.php');
                }
            } else {
                $err = '<tr><td colspan="2">'
                     . '<div class="error-message">The username and/or password you entered is invalid.</div>'
                     . '</td></tr>';    
            }
            
        } else {
            $err = '<tr><td colspan="2">'
                 . '<div class="error-message">The username and/or password you entered is invalid.</div>'
                 . '</td></tr>';
        }
    }
}
?>

Initial URL

                                

Initial Description

                                

Initial Title
Login & Start Session

Initial Tags
login

Initial Language
PHP