• 12Mar

    This tutorial goes over the concept of a log in system with MySQL with sessions. (The sources are provided after the jump)
    One of my viewers sent me a message on youtube requesting this great example

    Dear kloplop321,
    I really want to make a php, mysql based game. I have an idea about how I am going to do it. I would just really love some help with the SESSION login. There are tutorials on the internet but I find that they don’t show the full code or stuff like that. So if you would please create a tutorial on it I would apprecitate it. Thanks.

    This tutorial naturally has the sources provided.

    The following videos(2) go over the concept of a login system in PHP while using sessions(to maintain the login status) and MySQL(a database that holds the information). I first go over how to make

    • the login page
    • the table in the database
    • a user through PHPMyAdmin [the next tutorial will likely go over registering users]
    • code how to validate that user and if they are validated
    • if so, set the session information
    • if acceptable, they can go to a “members only” page [which only allows identified people in]
    • a way to log out

    Again: this tutorial is pretty much a walk-through in concept of a mysql login system.

    Part 2 (the most important) and the sources after the jump.

    And now the sources.
    include.php


    <?php
    session_start
    ();//start the session
    //now to do the MySQL connection.
    $link mysql_connect('localhost''phpuser''phppass');
    if (!
    $link) {
        die(
    'Could not connect: ' mysql_error());
    }
    //WE NEED to select the database!
    mysql_select_db("tutorials_login");

    ?>


    index.php


    <?php
    include("include.php");
    //see if the person is trying to log in now..
    if(isset($_REQUEST['sub'])){
        
    $username trim($_REQUEST['username']);
        
    $password trim($_REQUEST['password']);
        
    //make it safe to see if in the table
        
    $username mysql_real_escape_string($username);
        
    $password md5($password);
        
    //time to query
        
    $sql "SELECT * FROM `users` WHERE username = '$username' AND password = '$password'";
        
    $result mysql_query($sql);
        
    $exists false;
        
    $userid = -1;
        while(
    $row mysql_fetch_array($result)){
            
    $exists true;
            
    $userid = (int)$row[0];
            break;
    //get out of the while loop
        
    }
        if(
    $exists){
            
    $_SESSION['isin'] = 1;
            
    $_SESSION['userid'] = $userid;
        }else{
            echo 
    "You got something wrong, try again<br />\n";
            
    //echo $sql;
        
    }
    }
    //chopsuey

    //detect if logged in via variable in the session
    if($_SESSION['isin'] == 1){
        
    //we are logged in.
        
    echo "Hey there, you seem to be logged in,
        Would you like to go to the <a href=\"membersonly.php\">Members Only</a> area?<br /> Or would you want to
        <a href=\"logout.php\">log out</a>?"
    ;
    }else{
        
    //show the login prompt
        
    ?>
        <form action="?" method="post">
            Username <input type="text" name="username" /><br />
            Password <input type="password" name="password" /> <br />
            <input type="submit" value="Log in" />
            <input type="hidden" name="sub" value="1" />    
        </form>
        <?php
    }
    ?>


    logout.php


    <?php
    session_start
    ();
    session_destroy();
    header("location: index.php");
    ?>

    membersonly.php


    <?php
    include("include.php");
    if(
    $_SESSION['isin'] == 1){
        echo 
    "Hey there ";
        
    $sql "SELECT * FROM users WHERE id = ".$_SESSION['userid'];
        
    $result mysql_query($sql);
        
    $info null;
        while(
    $row mysql_fetch_array($result)){
            
    $info $row;
        }
        echo 
    $info['username'];//hey there pickles
        
    echo " Would you like to <a href=\"index.php\">go back</a>? ";
        
    }else{
        
    //you don't belong here, kick back to the index
        
    header("location: index.php");
    }
    ?>


    Also a tid bit of information: I did this in Linux, and I recorded it in 1080p HD!

    Posted by Kloplop321 @ 10:12 pm

    Tags: , , , , ,

19 Responses

WP_Orange_Techno
  • Charles Says:

    Very nice tutorial!

  • Haley Schillig Says:

    I’m currently still in the making of a website.
    When will you post the registering part?
    Out of everyones, your tutorials are the only ones that work and I WOULD LOVE to see the registering part.
    Your tutorials are so easier to understand and very organized.
    And I think the login system is the hardest part because it’s what your whole site is about..
    Please email me back and let me know if you are going to make a tutorial for the registering part (:
    I sure hope you are still giving out tutorials. Thanks so much<3

  • John Says:

    This tutorial was extremely distracting and ultimately useless. I’m sure the information is good enough, but your windows are transparent, your background changes every minute, and the camera follows the mouse around while we’re attempting to read your code… this was completely unwatchable.

  • Kloplop321 Says:

    I am sorry about that. I learned from that, thanks to commentators like you from youtube. I have been trying to minimize all distractions like that as I have been working on my future tutorials.

  • Sivaeb Says:

    For some reason I keep getting an Error…
    Notice: Undefined index: isin in C:\wamp\www\neighborhoodbusinessguide\index.php on line 30

  • Sivaeb Says:

    It seems to be when I log out or are not logged in.

  • Kloplop321 Says:

    This usually happens when you have a variable in the SESSION that doesn’t exist right now
    So like $_SESSION['username'], the username variable obviously will not be available when the user is not logged in. So, in order to address this issue,
    you do
    if(isset($_SESSION['username'])){
    //do code here
    }
    this checks to see if the variable exists(is set) then you are safe to access it. This is only a notice, so it doesn’t matter much in the long run.
    The reason why you are seeing notices is because in your php.ini (php settings file) the error reporting is most likely set to E_ALL, you can change it to E_ERROR and just have a filter so you don’t see the notices. I have the error reporting so it doesn’t show these notices.

    As you can see by my tutorial, I am only seeing if the session variable, isin, is set to 1.
    if($_SESSION['isin'] == 1){
    Now, if the variable does not exist(undefined index, meaning isin doesn’t exist), then it will return false for that variable.
    The computer now sees it as
    if(false == 1)
    logically false is 0, and 0 is not 1, so it does not execute the code that should happen when ‘isin’ is set to true or 1.

    Does that help your understanding?

  • Sivaeb Says:

    Yes it clear it up thanks

  • PHP Tutorials By Kloplop321 » Blog Archive » PHP & MySQL Tutorial 12: Logging into a Basic Blog Says:

    [...] future tools for the blog administration that will be shown in future tutorials. You may refer to Tutorial 8(Login Concept) as we go though this [...]

  • Steini Says:

    Thank’s for your tutorials. I’ve been going through some of them to learn php by making a blog. Great stuff. Your tutorials are also definitely improving although distracting things like transparent windows, changing desktop images and speech to text have not helped in some of them.

    Still you beat the resources offered by my master’s program without trying to sell me anything :) Good job!

  • Steini Says:

    One question: What editor are you using and does it work on windows?

  • Kloplop321 Says:

    Yep! I use Komodo Edit. It is Free, works on Windows, Mac, and Linux(My favorite)
    I also randomly posted about it on new years
    http://kloplop321.com/php-tutorials/index.php/2010/01/01/happy-new-years/
    You may find the link to it in that post :D

  • Steini Says:

    Thank’s

  • iijimae Says:

    Hello, I have encountered the error below. Can you please tell me what’s wrong? Though I can still successfully log in and log out with the error appeared.

    ( ! ) Notice: Undefined index: isin in D:\wamp\www\login\index.php on line 30

  • Kloplop321 Says:

    Okay, Just to help you understand for future reference, there are different levels of errors

    Fatal(Your page dies, it can’t recover)
    Warnings (They tell you that something might be done wrong and something needs to be changed
    Notices (They help you write your code better)

    I usually turn warnings and notices off so that I can just go over the concepts in my tutorials
    Its because its looking for that ‘index’ called ‘isin’ within the session array
    you can replace
    if($_SESSION['isin'] == 1){
    with
    if(isset($_SESSION['isin'])){
    and it should solve your notice problem.

  • iijimae Says:

    Oh i got this after i replace that :S
    ( ! ) Notice: Undefined variable: _SESSION in D:\wamp\www\login\index.php on line 30

    Can you teach me how to switch off the warnings and notices?

    I would like to start of with zend framework. Any recommendation(links or videos) on where to start of and how to install the zend?

    This blog is really awesome. I can learn up php easily starting from zero knowledge before this. Thanks for sharing your information here! :)

  • iijimae Says:

    And I have another question to ask. Let’s say i have direct my link from the main folder(name: login) to another folder(name: abc). And I tried to get back to index page by

    Go back to the main page

    But I found out it is not working cause it says there’s no index.php in the folder abc. Is there any way how to direct a link back to index in the main folder?

    Thanks!

  • iijimae Says:

    Oh yea I have solve the notice problem. Thanks a lot. And hope you will reply my questions above thanks :)

  • Kloplop321 Says:

    Sorry for the delay.
    Well, I’m not quite sure what you mean exactly, so I’ll just review the basics here
    if you are at
    somesite.com/ and this is your main folder,
    you have a section called abc, which is
    somesite.com/abc/
    If you wanted to link back to the main page, well you could say the link’s href=”../” which will go to the parent directory.
    However, if you know for sure that your main folder will be on somesite.com/ and only /, then you can say
    href=”/”
    But, lets say your main folder is like
    somesite.com/login/
    well, to go to somesite.com/abc/ from there, you may say
    href=”../abc”, and likewise, while in /abc/ you do href=”../login”
    If you do not have an index.php in one of the folders, well, you don’t have to state it. Your server’s configuration has a basic list of files to check for when it comes to the index, if none of these files are found, then it will go and follow one of the other rules, like listing the contents of the folder. However, most production servers usually do not have that enabled, so it will give a 503(not allowed) error, when the user tries to visit it.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.