www.webdeveloper.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 36

Thread: Creating a membership login

  1. #1
    Join Date
    Feb 2010
    Posts
    30

    Creating a membership login

    Needing some assistance with a client's site

    They are a martial arts school that is looking to setup a section for their members to review their belt class requirements and view videos.

    There will probably be only one database with one table for all the members and in it will be path to the page for that belt class.

    It has been a while since I dealt with a database so I was wondering if anyone can tell me how to accomplish it.
    Thanks

  2. #2
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    are you looking for a step by step tutorial on building a login? do you know php?

  3. #3
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    1. you need to build the data base.

    2. build a connect.php file to connect to the database.
    Code:
     <?php
    
      $connection = mysql_connect("localhost","root","") or die ("Could not connect to database."); 
        mysql_select_db("database here ") or die ("Could not find database."); 
    
    ?>
    3. build a registration form to sign up and submit authenticate the users account. action register.php

    4. build a sign in form which takes them to the page you want to give them access to. authenticate.php

    5. make a dynamic link which changes from login to logout on session_start();

  4. #4
    Join Date
    Feb 2010
    Posts
    30
    Hey Nick.
    I know some php coding; however I have never built a registration form or login for php. Can you suggest any tutorials or sites that will assist
    Jeff

  5. #5
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    all i can suggest is you tube videos.

    i could send you the code but you would still have to edit it to work with your site...

  6. #6
    Join Date
    Feb 2010
    Posts
    30
    Sure you can send it and I will have a look at it.

  7. #7
    Join Date
    Dec 2011
    Posts
    163
    Just an FYI, Lynda.com - PHP and MySQL Essential Training has a section on this, but I think the whole tutorial is something to learn. The login is quite nice and simple.

  8. #8
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    Ya I can post code for a login I have but I feel like with out going through it line by line it won't help you.

    You need to look up a tutorial on building a login in php basic. Then when you understand that you can add more complexed features to it. This is something you can learn in a day

    But then agAin if you just want it done send me a zip file of your site and ill add it for you.
    Nichodiaz@nichodiaz.com

    But... I strongly suggest you take 1 night or day and learn this your self. Once functionality is added it can always be updated or upgraded to something a little more advanced.

    The important thing is you go through this once and you never have this problem again.

  9. #9
    Join Date
    Feb 2010
    Posts
    30
    So I have setup all the files needed to login; however when I try to login it does not go anywhere it just gives me a blank screen.
    You can have a look a elitekenpo.org/login.php and I have created a test user for test and the password is temp123.

  10. #10
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    once you build a login you need to tell the authentication where to direct you at the point of success. or in the case of fail.

    there are different ways you can go about this. A few options...

    1. it takes you to a page only accessable to people whoa are logged in.
    2. it redirects you to any page in the website.
    3. a message pops up thats says you have logged in.

    remember you want to use php at this point to create a dynamic link which will change from login to logout. the logout button should end session. and when you authenitcate a login in make sure that is has session start at the top of the page.

    notice at the top of the authenticate page it has a session_start and at the end of the authenticate.php file it says header then a location and file path. thats where it takes u when u login and when u log out it destroys the session and takes u back to the index.php page

    on your page login.php the form action is targeting its self. this means you need the page to contain the equivilant to my authenticate.php file on it. otherwise you could make login.php the page with the login form on it then change the action to submit to a page like my authenticate.php

    here is an example of my php script for logging in. this file is called authenticate.php

    Code:
       <?php session_start(); error_reporting(0);
    $username = strip_tags(stripslashes($_POST['username'])); 
    $password = strip_tags(stripslashes($_POST['password'])); 
    include ("connect.php") ;
    $query = mysql_query("SELECT id, isadmin, username, first, last, password, email FROM members WHERE ((username = '" . mysql_real_escape_string($username) . "' || email = '" . mysql_real_escape_string($username) . "') && password = '" . mysql_real_escape_string(sha1($password)) . "') LIMIT 1"); 
    if(mysql_num_rows($query) == 1){
    $row = mysql_fetch_array($query);
    mysql_query("UPDATE members SET lastLoginTime = '" . time() . "' WHERE id = '" . $row['id'] . "' LIMIT 1");//update table with member's last login time//
    mysql_query("UPDATE members SET lastLoginDate = '" . date('F j, Y') . "' WHERE id = '" . $row['id'] . "' LIMIT 1");//update tabel with member's last login date//
    $_SESSION['id'] = $row['id'];
    $_SESSION['username'] = $row['username']; 
    $_SESSION['first'] = $row['first'];
    $_SESSION['last'] = $row['last'];
    $_SESSION['email'] = $row['email'];
    $_SESSION['isadmin'] = $row['isadmin'];
    $_SESSION['sessionTime'] = time();//create this session var for time to account for 60 minutes of inactivity//
    header("Location:../dashboard.php");
    }else{
    echo "Login Failed Please try again";
    };
    ?>
    here is my example of logging out logout.php

    Code:
      <?php
    session_start();
    
    session_destroy();
    
    header ("Location:../index.php");
    ?>
    Last edited by Nicholas Diaz; 06-11-2013 at 09:32 AM.

  11. #11
    Join Date
    Feb 2010
    Posts
    30
    Okay, so question? Is it possible to put the link in the database so when it accessing the user it will redirect to the page that is displayed in the database. So the client wants that the student only see one page until they complete their belt test and than them or myself would change it to the next belt level page in the database for that student. Is that possible?

  12. #12
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    yes there is a few ways to accomplish that. what you would do is add user privileges in the database.

    first thing is first. do you understand how to get the login working and the header pointing to the first page you want to direct the user too? once we have this working we can work on the next page

    one way of doing this is by adding a column in the database that contains a value. when a user logs in with his username and password we can query the database with php and have it grab the URL stored for the specific user and have him directed to the correct page.

    But I would start by making sure we can get your login working first, and im sure we can brain storm a better system than that so you dont have to keep going in to mysql and changing stuff manually.

    one option which i recently used for something similar is i added a code field in the registration field. basically the owner of the company has to give you a code for you to register on his website.

    we can add a code field and when you log in there can be a place for a code. and you can give out the specific code to the people you want to see which ever page.

    but this will also depend on how many pages you have, we should look at the full objective and brain storm a solution that makes sense according to the project.
    Last edited by Nicholas Diaz; 06-11-2013 at 10:14 AM.

  13. #13
    Join Date
    Feb 2013
    Posts
    91
    I don't mean to muddy up this even more, but I wrote a nice login/registration tutorial (without authentication though it could easily be implemented).

    common.inc.php file:
    PHP Code:
    <?php
    //Start session        
    session_start();    
    // create an user $_SESSION array:
    $_SESSION['user'] = NULL;
    // Set error message to Null
    $errMsg NULL;        
    // Create the database connection as a PDO object:
    try {
        
        
    $db_options = array(
               
    PDO::ATTR_EMULATE_PREPARES => false                     // important! use actual prepared statements (default: emulate prepared statements)
               
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION           // throw exceptions on errors (default: stay silent)
               
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC      // fetch associative arrays (default: mixed arrays)
           
    );          
        
        
    $pdo = new PDO('mysql:host=localhost;dbname=demo_login_system;charset=utf8''your_username''your_password'$db_options);    
        
    } catch (
    PDOException $e) { // Report the Error!
        
        
    $errMsg "<p>Something is not right, check your php.ini settings or code</p>";
        
    }        

    // A nice little function that sanitizes the data output:
    function html_escape($raw_input) {
       return 
    htmlspecialchars($raw_inputENT_QUOTES ENT_HTML401'UTF-8');     // important! don't forget to specify ENT_QUOTES and the correct encoding
    }
    The next two file use common.inc.php which I put in folder called includes (though I would change it on a live website .... assuming this code is used)

    register.php:
    PHP Code:
    <?php
    /*
        ********* TABLE Structure *********
        CREATE TABLE IF NOT EXISTS `users` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `username` varchar(30) NOT NULL,
          `password` char(60) NOT NULL,
          `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
    */

    // common.inc.php file contains required
    // database connection  & initialization info:
    require 'includes/common.inc.php';

    // A nice password hashing library for PHP 5
    // Find it here: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php
    // Read the Documentation for further help:
    // NOTE: if you're not using PHP 5, there are plenty of 
    // other good password hashing libraries out there ---> JUST GOOGLE IT!
    require 'includes/password.inc.php';

                  
    // Check to see if user has submitted form:
    if (isset($_POST['action']) && $_POST['action'] == 'register') {
        
        
    // Grab the user's input from form:   
        
    $username $_POST['username'];
        
    $password $_POST['password'];

        
    // Using Regex to check username:
        
    if (preg_match("/^[0-9a-zA-Z_]{5,}$/"$username) === 0) {
            
    $errMsg '<p>Username must be bigger that 5 chars and contain only digits, letters and underscore<p>';
        }
        
        
    // Using Regex to check password: 
        
    if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/"$password) === 0) {
            
    $errMsg .= '<p>Password must be at least 8 characters, and must contain at least one lower case letter, one upper case letter and one digit.</p>';        
        }
        
        
    // Function to check if username is available:
        
    function isUsernameAvailable($username$pdo) {    
            
            
    // The PDO Query:   
            
    $query "
                SELECT
                    1
                FROM users
                WHERE
                    username = :username1
            "
    ;
           
            
    // The prepared property/attribute:
            
    $query_params = array(
                
    ':username1' => $username
            
    );    

            
    // These two statements run the query against your database table.
            
    $stmt $pdo->prepare($query);
            
    $result $stmt->execute($query_params);

            
    // The fetch() method returns an array representing the "next" row from
            // the selected results, or false if there are no more rows to fetch.              
            
    return $row $stmt->fetch();       
            
    // If a row was returned, then we know a matching username was found in
            // the database already and we should return a boolean value back.       
                            
        
    }
        
        
    // Check to see if username is available:
        
    $result isUsernameAvailable($username$pdo);
        
        
    // If username is taken then assign to $errMsg:
        
    if ($result) {
            
    $errMsg .= '<p>Username: ' $username ' is already taken.</p>';            
        }
                   
        
    // Hash the password - See above for details:    
        
    $password password_hash($passwordPASSWORD_BCRYPT, array("cost" => 15));    

        
    // Store user's credentials, if form data is validated:
        
    if(!$errMsg) {
           
    // Using prepared statements:                  
           
    $query 'INSERT INTO users ( username, password ) VALUES ( :username, :password )';
           
    $stmt $pdo->prepare($query);
           
    $result $stmt->execute(array(':username' => $username':password' => $password));             
           
    $errMsg 'You have successfully registered to our great website!';                    
        }       

    }
    ?>
    <!--/Display Errors if there are any - using a ternary operator-->
    <?php echo (isset($errMsg)) ? $errMsg '<h1>Registration Page</h1>'?>

    <form action="register.php" method="post"/>

    <input type="hidden" name="action" value="register" />

    Username: <input type="text" name="username"/><br />
    Password: <input type="password" name="password"/><br />
    <input type="submit" value="register!"/>
    </form>
    login.php:
    PHP Code:
    <?php
    // common.inc.php file contains required
    // database connection initialization info:
    require 'includes/common.inc.php';

    // A nice password hashing library for PHP 5
    // Find it here: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php
    // Read the Documentation for further help:
    require 'includes/password.inc.php';

    if (isset(
    $_POST['action']) && $_POST['action'] == 'login') {

         
    // This query retreives the user's information from the database using
         // their username.
        
    $query '
                SELECT
                    id,
                    username,
                    password,
                    DATE_FORMAT(date_added, "%e %M %Y") as date_added
                FROM users
                WHERE
                    username = :username
                '
    ;
            
        
    // The parameter values
        
    $query_params = array(
            
    ':username' => $_POST['username']
        );        
        
        
        try
        {
            
    // Execute the query against the database
            
    $stmt $pdo->prepare($query);
            
    $result $stmt->execute($query_params);
        }
        catch(
    PDOException $ex)
        {
            
    // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code. 
            
    die("Failed to run query: " $ex->getMessage());
        }
        
        
    // This variable tells us whether the user has successfully logged in or not.
        // We initialize it to false, assuming they have not.
        // If we determine that they have entered the right details, then we switch it to true.
        
    $login_ok false;        

        
    // Retrieve the user data from the database.  If $row is false, then the username
        // they entered is not registered.
        
    $row $stmt->fetch();
        
        if(
    $row)
        {
            
    // Verify Stored Hashed Password:
            
    $result password_verify($_POST['password'], $row['password']);
            
            if (
    $result) {
                
    $login_ok true;    
            } else {
                
    $errMsg '<p>Your credientials do not match!</p>';
            }
                      
        }
        
        
    // If login is OK:
        
    if ($login_ok) {
            
            
    // It's not wise to store the password in $_SESSION:
            
    unset($row['password']);    
            
            
    // This stores the user's data into the session at the index 'user'.
            // We will check this index on the private members-only page to determine whether
            // or not the user is logged in.  We can also use it to retrieve
            // the user's details.
            
    $_SESSION['user'] = $row;
            
            
    // The following output is just to prove that it works:
            
    echo '<pre>';
            
    print_r($_SESSION);
            echo 
    '</pre>';
            
            
    // Redirect the user to the private members-only page.
            //header("Location: admin.php");
            //die("Redirecting to: admin.php");        
        
    }
        
    }
    /*
     *  This was just to help people who are just getting started
     *  learning how to program in the PHP Language. The PDO portion
     *  is written in Object-Oriented Style, but this doesn't mean
     *  that you now know OOP or that you have to use it. It's pretty
     *  straight forward in my opinion. I have tested this out, but I make
     *  no guarantees that it works 100 percent and it diffentely needs
     *  updating/styling. However, that is up to you and besides it's 
     *  a good way to learn PHP.  
     */
    ?>

    <!--/Display Errors if there are any - using a ternary operator-->
    <?php echo (isset($errMsg)) ? $errMsg '<h1>Login Page:</h1>'?>

    <form action="login.php" method="post"/>

    <input type="hidden" name="action" value="login" />

    Username: <input type="text" name="username"/><br />
    Password: <input type="password" name="password"/><br />
    <input type="submit" value="submit"/>
    </form>

    This is far from perfect, but I do know one thing that it works. Even if none of the code is used, I think it shows how to go about writing a basic login/registration system in PHP. I didn't take in the part of sanitizing the variables, but it is using PDO prepared statements.
    Last edited by Strider64; 06-11-2013 at 10:42 AM.

  14. #14
    Join Date
    Feb 2010
    Posts
    30
    Yeah. I got that from you before Strider. And I copied everything over; however it is not logging in. Or I should say it is; however I am getting a blank screen

  15. #15
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    that code is not working. its authenticating anything we type in.

    u need to make sure you have your database set up correctly.

    u need to make sure your declaring the header section upon authentication

    do u have the database set up?

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
  •  
HTML5 Development Center



Recent Articles