user authenication/login help
Results 1 to 8 of 8

Thread: user authenication/login help

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    5

    user authenication/login help

    hello all, first post here.

    im fairly new to php and am still trying to really get a hold of what im doing. right now im just trying to build a simple login function for my site and am completely stuck.
    here is what i have so far.

    in function authuser im trying to create a query, return the result, compare it with those that were posted on index.php and if it matches the database i would like the login function. to start the session.
    i hope that makes sense.

    index.php
    PHP Code:
    if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username $_POST['username'];
    $password md5($_POST['password']);

    if(empty(
    $username) || empty($password)){
    $data['status'] = 'Please fill out both inputs';
    } else {
    // login
    authuser($username,$password);
    }

    functions.php
    PHP Code:
    function login($username,$password)
    {
    session_start();
    }

    function 
    authuser($username,$password)
    {
    $sql "SELECT * FROM users WHERE username='$username' and password='$password'";
    $results mysql_query($sql);
    $rows mysql_num_rows($results);

    if(
    $rows==1)
    {
    session_register("admin");
    } else {
    echo 
    "Wrong Username or Password";
    }


  2. #2
    Senior Member traq's Avatar
    Join Date
    Jun 2011
    Location
    so.Cal
    Posts
    949
    some notes...

    You're not checking if "username" or "password" actually exist before using them. This will cause errors if they're missing (also consider that, in your current code, $password will never be empty - even if the user left the field blank).

    I don't know how you'd prefer to handle errors/user messages, but you should choose one way. Right now, you're saving the messages for later in some cases and simply dumping output to the browser in others.

    Why does your login() function require a username and password, when it does nothing except call session_start()? Why have this function at all?

    Don't use the mysql_*() functions. They are deprecated. You should use mysqli or PDO instead.

    Why select all columns from your matching rows when your function doesn't use any of it? You could SELECT 1 ... instead. If you plan to use the info later, you should write out the column names explicitly (using * in production is almost never the best approach).

    Don't use session_register(). It is also deprecated and has some major caveats in its use that can cause unexpected problems. Use the $_SESSION superglobal instead.

    Maybe something like this?
    PHP Code:
    <?php
    session_start
    ();

    # This assumes this script does nothing but process your login form.
    # check required fields
    if( empty( $_POST['username'] ) || empty( $_POST['password'] ) ){
        
    $msg 'Please fill out both fields to log in.';
    }else{
        
    # this example uses mysqli.
        
    $DB = new mysqli'DB_host','DB_username','DBpassword','DB_name' );

        
    # check if login is correct:
        
    $success check_login$_POST['username'],$_POST['password'],$DB );

        
    # assign appropriate message:
        
    $msg $success?
            
    'Thank you for logging in':     // success
            
    'Wrong username or password.';  // failure

        # you might do other stuff based on success or failure here;
        # e.g., save user info to the $_SESSION superglobal, etc..

    }
    # user message
    print $msg;

    /**
     * this function checks a username and password against database records.
     * 
     * @param string $username        The username to check
     * @param string $password        The password to check
     * @param object $DB              The database connection object
     *                                (This example uses the mysqli extension [http://php.net/mysqli])
     * @return bool                   true if username+password matches a DB record; flase otherwise.
     */
    function check_login$username,$password,mysqli $DB ){
        
    # use a prepared statement; this helps prevent SQL injection attacks
        
    $query $DB->prepare'SELECT 1 FROM users WHERE username=? AND password=?' );

        
    # do your hash (*just* md5() isn't the best approach, BTW)
        
    $password md5$password );

        
    # bind the submitted username/password to the statement
        
    $query->bind_param'ss',$username,$password );

        
    # query the DB and check number of rows returned to determine success
        
    $result $query->execute();
        return (
    $result->num_rows === 1)?
            
    true:   // 1 row means you found a match
            
    false;  // otherwise, the check failed.
    }

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    5
    sorry it took so long to respong,
    but thanks for your suggestions it seems to be working with a few bugs however
    right now when i pass the username and password i get back this error

    "Trying to get property of non-object in C:\wamp\www\whatscookincatering\lib\functions.php on line 23"

    here is what my code looks like now

    index.php
    [PHP]
    <?php

    require '../blog.php';
    $data = array();

    session_start();

    # check required fields
    if( empty( $_POST['username'] ) || empty( $_POST['password'] ) ){
    $data['msg'] = 'Please fill out both fields to log in.';
    }else{
    $DB = new mysqli( 'localhost', $config['dbusername'], $config['dbpassword'], $config['database'] );

    # check if login is correct:
    $success = check_login( $_POST['username'],$_POST['password'],$DB );

    # assign appropriate message:
    $data['msg'] = $success?
    'Thank you for logging in': // success
    'Wrong username or password.'; // failure

    }

    view('../admin/login', $data);
    ?>
    PHP Code:
    <?php  
    function view($path$data null)
    {
        if ( 
    $data ){
            
    extract($data);
        }

        
    $path 'views/' $path '.tmpl.php';

        include 
    "../views/layout.php";
    }

    function 
    check_login$username,$password,mysqli $DB )
    {
        
    $query $DB->prepare"SELECT 1 FROM users WHERE username=? AND password=?" );
        
    $password md5$password );

        
    # bind the submitted username/password to the statement
        
    $query->bind_param'ss',$username,$password );

        
    # query the DB and check number of rows returned to determine success
        
    $result $query->execute();
        return (
    $result->num_rows === 1)?
            
    true:  
            
    false;  
    }
    ?>

  4. #4
    Junior Member
    Join Date
    Feb 2013
    Posts
    5
    "sorry for the double post, i dont see an edit post option"
    this is line 23

    "return ($result->num_rows === 1)?"

  5. #5
    Senior Member traq's Avatar
    Join Date
    Jun 2011
    Location
    so.Cal
    Posts
    949
    my bad.

    change this:
    PHP Code:
    # query the DB and check number of rows returned to determine success 
        
    $result $query->execute(); 
        return (
    $result->num_rows === 1)? 
            
    true:   
            
    false
    to this (tested; works):
    PHP Code:
    # query the DB and check number of rows returned to determine success 
        
    $query->execute(); 
        
    $query->store_result();
        
    $result = ($query->num_rows === 1)? 
            
    true:   
            
    false;
        
    $query->close();
        return 
    $result
    I was using the prepared statement wrong. Sorry about the confusion.

  6. #6
    Junior Member
    Join Date
    Feb 2013
    Posts
    5
    well now the problem seems to be that no matter what value i put in it gives me the wrong username/password message,
    i dont see why though because im only selecting 1 row in the mysqli statment so it should be returning the true value, but its not.
    any ideas as to why not?

  7. #7
    Senior Member traq's Avatar
    Join Date
    Jun 2011
    Location
    so.Cal
    Posts
    949
    ...first thing I'd do is make sure there really is a matching record in the DB. That's the problem more often than you might think, especially in development where records might not have all been input the same way.

    Use a tool like PHPMyAdmin to select a username + password and assign the values manually:
    PHP Code:
    function check_login$username,$password,mysqli $DB ){ 
        
    # use a prepared statement; this helps prevent SQL injection attacks 
        
    $query $DB->prepare'SELECT 1 FROM users WHERE username=? AND password=?' ); 

    ###
    #     skip the hash for this test (because we're already using the hashed value from the DB)
    #
    #    $password = md5( $password ); 
    #
    #     don't forget to change this back later
    ###

        # bind the submitted username/password to the statement 
        
    $query->bind_param'ss',$username,$password ); 

        
    # query the DB and check number of rows returned to determine success 
        
    $query->execute(); 
        
    $query->store_result();
        
    $result = ($query->num_rows === 1)? 
            
    true:   
            
    false;
        
    $query->close();
        return 
    $result;  

    }
    if( 
    check_login'knownUserName','knownPasswordHash',$DB ) ){ print "all good"; }else{ print "whoops!"; } 
    The other possibility is that there is more than one row returned (more than one match).
    This shouldn't be, since each username (or, at the very least, each username+password combination) should be unique.

  8. #8
    Junior Member
    Join Date
    Feb 2013
    Posts
    5
    it seems to be that it was posting an md5 password but the password in the database wasnt encrytped other than that it seems to be working great,

    now i just have to figure out how to take this value as true and redirect me to a different page. or at least a different view.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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