SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Wizard Busch's Avatar
    Join Date
    Jan 2004
    Posts
    1,072
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP Anthology: Auth Class problems

    I have been reading/using the PHP Anthology series to help me rebuild a website. Everything has been great, until now. I have hit a wall and can't seem to get around it.

    My problem comes when implementing the Auth Class (Volume II, Page 13 - 24, Scripts 4.php & 5.php & Auth.php). I can successfully register and login, that's not the issue. The issue is the "redirects" within the Auth class either aren't working or I am not using them properly (most likely the latter ).

    When a user visits my page (not logged in) there are 2 <input> fields at the top of every page where there user can login any time. That, too is working fine, meaning it successfully logs the user in. But I can't get it to:

    A. Redirect back to the page the user logged in from
    B. Redisplay the form and error message if the login failed


    I know these things must be simple to accomplish because all the other classes have worked so perfectly. I can get things to work by storing URL's in $_GET and $_POST variables and applying functions like rawurlencode and urldecode to them but the code has become very sloppy, in my opinion. Has anyone figured out how to use the Auth Class more effectively?


    Below are the 3 scripts in question in case you don't have the book.

    4.php
    PHP Code:
    <?php
    // If $_GET['form'] comes from the Auth class
    if ( isset ( $_GET['from'] ) ) {
        
    $target=$_GET['from'];
    } else {
        
    // Default URL: usually index.php
        
    $target='5.php';
    }
    ?>
    <!doctype html public "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title> Login Form </title>
    <meta http-equiv="Content-type"
        content="text/html" charset="iso-8859-1" />
    <style type="text/css">
    body, a, td, input
    {
        font-family: verdana;
        font-size: 11px;
    }
    h1
    {
        font-family: verdana;
        font-size: 15px;
        color: navy
    }
    </style>
    </head>
    <body>
    <h1>Please log in</h1>
    <form action="<?php echo ( $target ); ?>" method="post">
    <table>
    <tr valign="top">
    <td>Login Name:</td>
    <td><input type="text" name="login" /></td>
    </tr>
    <tr valign="top">
    <td>Password:</td>
    <td><input type="password" name="password" /></td>
    </tr>
    <tr valign="top">
    <td></td>
    <td><input type="submit" value=" Login " /></td>
    </tr>
    </table>
    </form>
    </body>
    </html>
    5.php
    PHP Code:
    <?php
    // Include Magic Quotes stripping script
    require_once('MagicQuotes/strip_quotes.php');

    // Include MySQL class
    require_once ('Database/MySQL.php');

    // Include Session class
    require_once ('Session/Session.php');

    // Include Auth class
    require_once ('AccessControl/Auth.php');

    $host='localhost';   // Hostname of MySQL server
    $dbUser='myName';    // Username for MySQL
    $dbPass='mySecret';    // Password for user
    $dbName='myDatabase'// Database name

    // Instantiate MySQL connection
    $db=& new MySQL($host,$dbUser,$dbPass,$dbName);

    // Instantiate the Auth class
    $auth=& new Auth ($db,'4.php','secret');

    // For logging out
    if ( isset ( $_GET['action'] ) && $_GET['action'] == 'logout' ) {
        
    $auth->logout();
    }
    ?>
    <!doctype html public "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title> Welcome </title>
    <meta http-equiv="Content-type"
        content="text/html" charset="iso-8859-1" />
    <style type="text/css">
    body, a, td, input
    {
        font-family: verdana;
        font-size: 11px;
    }
    h1
    {
        font-family: verdana;
        font-size: 15px;
        color: navy
    }
    </style>
    </head>
    <body>
    <h1>Welcome</h1>
    <p>You are now logged in</p>
    <?php
    if ( isset ($_GET['action']) && $_GET['action'] == 'test' ) {
        echo ( 
    '<p>This is a test page. You are still logged in' );
    }
    ?>
    <p><a href="<?php echo ( $_SERVER['PHP_SELF'] ); ?>?action=test">Test page</a></p>
    <p><a href="<?php echo ( $_SERVER['PHP_SELF'] ); ?>?action=logout">Logout</a></p>
    </body>
    </html>
    Auth.php
    PHP Code:
    <?php
    /**
    * @package SPLIB
    * @version $Id: Auth.php,v 1.7 2003/12/09 06:06:13 kevin Exp $
    */
    /**
    * Constants to modify behaviour of Auth Class
    */
    # Modify these constants to match the $_POST variable used in login form
    // Name to use for login variable e.g. $_POST['login']
    @define 'USER_LOGIN_VAR','login');
    // Name to use for password variable e.g. $_POST['password']
    @define 'USER_PASSW_VAR','password');

    # Modify these constants to match your user login table
    // Name of users table
    @define 'USER_TABLE','user');
    // Name of login column in table
    @define 'USER_TABLE_LOGIN','login');
    // Name of password column in table
    @define 'USER_TABLE_PASSW','password');
    /**
    * Authentication class<br />
    * Automatically authenticates users on construction<br />
    * <b>Note:</b> requires the Session/Session class be available
    * @access public
    * @package SPLIB
    */
    class Auth {
        
    /**
        * Instance of database connection class
        * @access private
        * @var object
        */
        
    var $db;
        
    /**
        * Instance of Session class
        * @access private
        * @var Session
        */
        
    var $session;
        
    /**
        * Url to re-direct to in not authenticated
        * @access private
        * @var string
        */
        
    var $redirect;
        
    /**
        * String to use when making hash of username and password
        * @access private
        * @var string
        */
        
    var $hashKey;
        
    /**
        * Are passwords being encrypted
        * @access private
        * @var boolean
        */
        
    var $md5;
        
    /**
        * Auth constructor
        * Checks for valid user automatically
        * @param object database connection
        * @param string URL to redirect to on failed login
        * @param string key to use when making hash of username and password
        * @param boolean if passwords are md5 encrypted in database (optional)
        * @access public
        */
        
    function Auth ( & $db$redirect$hashKey$md5=true ) {
            
    $this->db=& $db;
            
    $this->redirect=$redirect;
            
    $this->hashKey=$hashKey;
            
    $this->md5=$md5;
            
    $this->session=& new Session();
            
    $this->login();
        }
        
    /**
        * Checks username and password against database
        * @return void
        * @access private
        */
        
    function login() {
            
    // See if we have values already stored in the session
            
    if ( $this->session->get('login_hash') ) {
                
    $this->confirmAuth();
                return;
            }

            
    // If this is a fresh login, check $_POST variables
            
    if ( !isset($_POST[USER_LOGIN_VAR]) ||
                    !isset(
    $_POST[USER_PASSW_VAR]) ) {
                
    $this->redirect();
            }

            if ( 
    $this->md5 )
                
    $password=md5($_POST[USER_PASSW_VAR]);
            else
                
    $password=$_POST[USER_PASSW_VAR];

            
    // Escape the variables for the query
            
    $login=mysql_escape_string($_POST[USER_LOGIN_VAR]);
            
    $password=mysql_escape_string($password);

            
    // Query to count number of users with this combination
            
    $sql="SELECT COUNT(*) AS num_users
                    FROM "
    .USER_TABLE."
                    WHERE "
    .USER_TABLE_LOGIN."='".$login."'
                    AND "
    .USER_TABLE_PASSW."='".$password."'";

            
    $result=$this->db->query($sql);
            
    $row=$result->fetch();

            
    // If there isn't is exactly one entry, redirect
            
    if ( $row['num_users']!=)
                
    $this->redirect();
            
    // Else is a valid user; set the session variables
            
    else
                
    $this->storeAuth($login,$password);
        }
        
    /**
        * Sets the session variables after a successful login
        * @return void
        * @access protected
        */
        
    function storeAuth($login,$password) {
            
    $this->session->set(USER_LOGIN_VAR,$login);
            
    $this->session->set(USER_PASSW_VAR,$password);
            
    // Create a session variable to use to confirm sessions
            
    $hashKey md5($this->hashKey.$login.$password);
            
    $this->session->set('login_hash',$hashKey);
        }
        
    /**
        * Confirms that an existing login is still valid
        * @return void
        * @access private
        */
        
    function confirmAuth() {
            
    $login=$this->session->get(USER_LOGIN_VAR);
            
    $password=$this->session->get(USER_PASSW_VAR);
            
    $hashKey=$this->session->get('login_hash');
            if (
    md5($this->hashKey.$login.$password) != $hashKey ) {
                
    $this->logout(true);
            }
        }
        
    /**
        * Logs the user out
        * @param boolean Parameter to pass on to Auth::redirect() (optional)
        * @return void
        * @access public
        */
        
    function logout ($from=false) {
            
    $this->session->del(USER_LOGIN_VAR);
            
    $this->session->del(USER_PASSW_VAR);
            
    $this->session->del('login_hash');
            
    $this->redirect($from);
        }
        
    /**
        * Redirects browser and terminates script execution
        * @param boolean adverstise URL where this user came from (optional)
        * @return void
        * @access private
        */
        
    function redirect($from=true) {
            if ( 
    $from ) {
                
    header 'Location: '.$this->redirect.'?from='.
                    
    $_SERVER['REQUEST_URI'] );
            } else {
                
    header 'Location: '.$this->redirect );
            }
            exit();
        }
    }
    ?>

  2. #2
    SitePoint Wizard Busch's Avatar
    Join Date
    Jan 2004
    Posts
    1,072
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Also in reference to this post: http://www.sitepoint.com/forums/show...79#post1122679 my php_sapi_name: apache

  3. #3
    does not play well with others frezno's Avatar
    Join Date
    Jan 2003
    Location
    Munich, Germany
    Posts
    1,391
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well, it works for me. you are starting with calling 4.php ?
    We are the Borg. Resistance is futile. Prepare to be assimilated.
    I'm Pentium of Borg.Division is futile.Prepare to be approximated.

  4. #4
    SitePoint Wizard Busch's Avatar
    Join Date
    Jan 2004
    Posts
    1,072
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by frezno
    well, it works for me. you are starting with calling 4.php ?
    Yes, i am starting with 4.php and i have no problem logging in. I can login, restrict access to certain page, etc...

    What I need to do is always have the login form at the top of each page. When the user decides to login (from any page on the site), if the login is valid they are redirected back to the page they came from. I hope that makes sense...

    Can you tell me what your login page looks like (ie. is it on its own page or available on every page) and how it functions in terms of redirecting back to the page the user logged in from? Any info would be really helpful!!! Did you make any changes to Auth.php or 4, 5.php?

  5. #5
    SitePoint Wizard Busch's Avatar
    Join Date
    Jan 2004
    Posts
    1,072
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Still no luck...

    I can login but I don't get redirected away from 5.php. I just get:

    Welcome
    You are now logged in
    Test page
    Logout


    QUESTIONS
    1. Is it supposed to redirect?
    2. Am I supposed to add some $_GET values on the end of any of my links?

    Here's are some snippets of what's going on. Do you see anything that I am doing wrong?

    Link to 4.php
    PHP Code:
    <a href="4.php">Login</a
    4.php
    PHP Code:
    // If $_GET['form'] comes from the Auth class
    if ( isset ( $_GET['from'] ) ) {
        $target=$_GET['from'];
    } else {
        // Default URL: usually index.php
        $target='5.php';
    }
    .
    .
    .
    <form action="<?php echo ( $target ); ?>" method="POST">
    5.php
    Same as 5.php in my first post

    Am I going about this totally the wrong way?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •