Results 1 to 12 of 12

Thread: [RESOLVED] Correct Way To Use Sessions

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Resolved [RESOLVED] Correct Way To Use Sessions

    Usually, I would create my own session "protocol" just using a username stored in the cookies, and the MD5 Hash of the password. Then when the user changes pages, PHP would check the user's cookies against the database and determine if they match or not. I know this is not a very secure way to do things, but I haven't been coding for anything major.

    I would like to however learn how to use SESSIONs properly. Let me give you an example of my code:


    Index Page:

    PHP Code:
    <?php

    include_once "includes/include.php"//Creates database links, and loads common functions for the script.

    session_start();

    if (
    isUserLoggedIn($userTableConn))
    {

      include 
    "the_index_page.php";

    }
    else
    {
        
      if (
    $_GET['userName']!="")
        {
        
          if (
    checkValidUser($_GET['userName'],md5($_GET['passWord']), $userTableConn))
            {
            
              
    $_SESSION['currentUser']=$_GET['userName']
              
    $_SESSION['currentUserPassword']=md5($_GET['passWord'])
            
            }
        
        }
        else
        {

            include_once 
    "login_page.php" // Just a normal login page with the username and password textboxes.

        
    }

    }
    ?>

    include.php:

    PHP Code:
    <?php 

    include_once "config.php" //Details for database access


    $userTableConn mysql_connect($dbHost$dbUsername$dbPassword) or die("Could not connect");
    mysql_select_db($dbDatabase,$userTableConn) or die("Could not select database");



    function 
    checkValidUser($userName$passWordHashed$dbConn)
    {

      
    $userQueryResult mysql_query("SELECT `Username`, `ID` FROM `membersTable` WHERE `Username`='" $userName "' && `Password`='" $passWordHashed "';"$dbConn);
        
    // Passwords are stored as MD5 HASHes inside the database. The MD5 HASH is sent to this function.

      
    if ($userQueryResult == FALSE)
      {
        echo(
    mysql_error());
      }
        
        
    $userQueryArray=mysql_fetch_array($userQueryResult);
        
        if (
    userQueryArray=="")
        {
          return 
    false;
        }
        else
        {
          return 
    true;
        }
        
    }


    function 
    isUserLoggedIn($dbConn)
    {

      
    checkValidUser($_SESSION['currentUser'], $_SESSION['currentUserPassword'], $dbConn)

    }

    the_index_page.php:

    PHP Code:
    <?php
    if (isUserLoggedIn($userTableConn))
    {

      
    // Webpage Content
        
    }
    else
    {

      
    header("Location: index.php"); // This will send them to the login page, since they are not logged in.

    }
    The problems that I have with this method is that when a user logs in, it takes them back to the login page. Then they have to either press refresh or press login again for the login to be successful. I believe this is because PHP doesn't have time to send, and retrieve the SESSION and COOKIE data? Just speculation here.

    The next problem is that if they click a link on any of the pages, the session data is cleared away (They are logged out). This also happens if they navigate to any page (Including the current page). What I mean to say is when pressing refresh, everything is OK. When Pressing enter on the address bar (Which will navigate to the current page) the user is logged out. When navigating to any hyperlinks, the user is logged out.

    Does anyone have any suggestions? I use Hostgator to test all my scripts.

    I know that this code is open to SQL injections and all that. I left out any input validation to keep it simple.
    Last edited by Slyke; Jan 20th, 2009 at 06:50 AM.

  2. #2
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Correct Way To Use Sessions

    you need to use the function session_start() on every page that you're going to be using sessions on. session_start() starts or RESUMES a session, so you have no reason for the "session_started" function that you made. just do it at the beginning of every non-include script before you send any output to the browser.

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Correct Way To Use Sessions

    I have an index file that includes the new page that they are navigating to.

    For Example, my code is basically like this:
    PHP Code:
    session_start()

    // Check if valid user and stuff here too.

    if ($REQUEST['page']=="home")
    {
      include_once 
    "home.php"
    }
    elseif (
    $REQUEST['page']=="anotherpage")
    {
      include_once 
    "anotherpage.php"
    }
    elseif (
    $REQUEST['page']=="about")
    {
      include_once 
    "about.php"
    }
    else
    {
      include_once 
    "index_page.php" // Default page

    Isn't that, in a way, starting the session no matter what page they are on?
    Also it doesn't explain why the session breaks when they press enter on the browser's address bar, or why they must refresh the login page .

    I have changed my code in the first post to start a session no matter what (Took out checking if a session had begin, and placed it before any of the code (Just after the include)).
    Last edited by Slyke; Jan 20th, 2009 at 06:51 AM.

  4. #4
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Correct Way To Use Sessions

    yes, though your code didn't indicate that before (I see you've edited it now!).

    is this a typo? in the checkValidUser function:
    PHP Code:
      if (userQueryArray==""

  5. #5
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Correct Way To Use Sessions

    if you would like: http://davidmiles.ca/php/sessions.zip

    this is a zip file of 5 quick files I made up using sessions (very simple, no database validation or anything) and everything works fine. if my last post indicating your typo doesn't help, you may want to upload these to your server and see if they run and work fine, just to make sure it's not your server?

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Correct Way To Use Sessions

    Quote Originally Posted by kows
    yes, though your code didn't indicate that before (I see you've edited it now!).

    is this a typo? in the checkValidUser function:
    PHP Code:
      if (userQueryArray==""

    It's not a typo, if the SQL query returns no results, then it returns an empty string correct? It doesn't return a False since a False returns when the statement fails?

    I'll checkout that zip .

  7. #7

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Correct Way To Use Sessions

    As far as I can tell, my code is the same, just a little more complicated, but does the same thing. I'll setup the database and test out the new script when I have some time .

  8. #8
    Hyperactive Member
    Join Date
    Jan 2009
    Posts
    448

    Re: Correct Way To Use Sessions

    Just as another note you can use:

    Code:
    if (empty(userQueryArray))
    That will check for an null value. If you would like an example of a session I can give you a good one. I always set a unique session value when it is registered to show whether they are logged in or not. like this:

    Code:
    $_SESSION['logged_in'] = true;
    Then on each page you can call this:

    Code:
    if($_SESSION['logged_in'] == false)
    {
    header("location:login.php"); //redirect to login page
    }
    else
    {
    //code to be show if they are logged in
    }
    If I helped you please rate me.

  9. #9
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: Correct Way To Use Sessions

    It's not a typo, if the SQL query returns no results, then it returns an empty string correct? It doesn't return a False since a False returns when the statement fails?

    I'll checkout that zip .
    No, no. I was pointing out that you are calling the constant "userQueryArray" instead of the variable "$userQueryArray," and was asking if that was a typo or not.

    Also, using empty() is completely unnecessary. It is an alternative, but there's no real reason to switch to using that function.

    Using a variable to store a boolean of whether you are logged in or not may make things easier and require you to not check user validation on every single page, but does not really help with any of the problems he's experiencing

  10. #10
    Hyperactive Member
    Join Date
    Jan 2009
    Posts
    448

    Re: Correct Way To Use Sessions

    From what I read in his post he was trying to learn how to properly use sessions, so therefore I was just helping him understand how to make best use of sessions. Also like I said the empty() was just another way to check a variable and is more commonly used and easier to read. Once again if he would like an example of session use I will give him one and he can work off of that.
    If I helped you please rate me.

  11. #11

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Correct Way To Use Sessions

    Yep! That was a typo! My bad .


    I've created what I think to be a working version of the SESSION code.

    When testing, you'll have to manually place the database name, username, and password into the config.php file.
    After that, checkout the install directory to setup the tables.

    In the admin directory you can add/remove users.

    I haven't tested this out yet, but plan to sometime this weekend when I get some time .
    Last edited by Slyke; Jan 23rd, 2009 at 10:19 AM.

  12. #12

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: Correct Way To Use Sessions

    Thanks guys, I fixed up all the bugs in my code, and it now works 100%. I learnt a lot figuring this out!

    Here's an attachment of the finished product.

    Remember:
    When using, you'll have to manually place the database name, username, and password into the config.php file.
    After that, checkout the install directory to setup the tables.

    In the admin directory you can add/remove users.
    Attached Files Attached Files

Posting Permissions

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



Click Here to Expand Forum to Full Width