SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Zealot skipdawg95's Avatar
    Join Date
    Oct 2004
    Location
    Strasburg, VA
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Session and Cookie Help!!!

    I'm having a hell of a time with this. Maybe someone else can tell me what's wrong. I'm trying to set up a website that requires someone to login and eventually log out. Based on how my code is set up now, everytime I login in to the site, I'm redirected back to the login page. I can't get any where with it! I've posted both my login code and the session header code that I have loaded for each page for authentication. Have no clue which one is causing the problem. Any ideas?

    Login Script:

    PHP Code:
    <?php
    require_once ('PHP Docs/connection.php');
    /*The following is designed to check the inputed user name and password.  If both are accurate, the user will be redirected to the members page.  If the information is not listed in the database the individual will recieve an error.*/
    if (isset ($_POST['userName'])) {
        if (
    $user mysqli_query($conn"SELECT * FROM userInfo WHERE userName = '$_POST[userName]' AND password = '$_POST[password]' AND active = '1'") or die ("Error performing mysql query!")) {
        
    $number mysqli_num_rows($user);
        }

    if (
    $number == 1)  {
    //This will generate a session ID.
        
    srand((double)microtime() * 1000000);
        
    $sess_id md5(uniqid(rand()));
    //Next, delete previous sesion entry.
        
    mysqli_query ($conn"DELETE * FROM sessions WHERE userName = '$_POST[userName]'");
    //Input new session information.
        
    mysqli_query ($conn"INSERT INTO sessions (userName, sessionID, lastUsed) VALUES('$_POST[userName]', '$sess_id', 'time()')");
    //Set cookie information.
        
    setcookie('username'$_POST[username], time() + 3600);
        
    setcookie('session'$sess_idtime() + 3600);
    //Redirect to main page.
        
    header("Location: Main.php");
        exit;
        } else {
            
    $message "The username and password you provided are incorrect, or you have not activated your account.<br>
                        Please enter the correct username and/or password, or contact support if you have not recieved an activation email.<br>"
    ;
            }
    }
    ?>
    Session page header script:

    PHP Code:
    <?php
    /*This script will determine if cookies and session ID are set from initial login.  If they are not set, the pages will not load, and the user will be required to login again.*/
    if(isset($_COOKIE['username']) && isset($_COOKIE['session'])) {
    //If the cookie is found, get session info from database.
        
    $qry mysqli_query ($conn"SELECT * FROM sessions WHERE userName = '$_COOKIE[username]' AND sessionID = '$_COOKIE[session]'");
        
    $rows mysqli_num_rows ($qry);
        if(
    $rows == 1) {
        
    //Session was found in the database, check validity.  If session lifetime has passed, seesion is invalid.
        
    $sess mysql_fetch_assoc($qry);   
        
    $time_limit time() - 3600;
            if(
    $sess['lastUsed'] < $time_limit) {
            
    //The session has expired remove cookies from both client & server side and redirect user to login page.
                
    setcookie('username'''time()-3600);
                
    setcookie('session'''time()-3600);
                
    mysqli_query ($conn"DELETE FROM sessions WHERE userName = '$_COOKIE[username]' AND sessionID = '$_COOKIE[session]'");
                unset(
    $_COOKIE);
                
    header('Location: login.php');
                } else {
                    
    //The cookie is still valid, extend its lifetime.
                    
    setcookie('username'$_COOKIE['username'], time() + 3600);
                    
    setcookie('session'$_COOKIE['session'], time() + 3600);
                    
    //Update the session info.
                    
    mysqli_query ($conn"UPDATE sessions SET lastUsed = 'time()' WHERE userName = '$_COOKIE[username]' AND session = '$_COOKIE[session]'");
                } 
            } else {
                
    //Failed to get session info. Assume session is invalid 
                    
    setcookie('username'''time()-3600);
                    
    setcookie('session'''time()-3600);
                    unset(
    $_COOKIE);
                    
    header('Location: login.php');
            }
        } else {
            
    //The cookie was not found.  Redirect user to the login page.
            
    header('Location: login.php');

    ?>

  2. #2
    SitePoint Addict launchcode's Avatar
    Join Date
    Dec 2004
    Location
    Bristol, UK
    Posts
    259
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Highly likely the cookie either isn't being set (easily checked), or isn't able to be read by the "are they logged in?" code. Could be down to something a simple as not specifying a path for the setcookie function.

    Quick test for you - first of all, use Firefox (if you don't already), get the Web Developer Extension (http://www.chrispederick.com/work/firefox/webdeveloper/) and login and check to see if the cookie was set or not.

    Second test - instead of just re-directing if the cookie isn't found - do another test. Dump out the cookie values (print_r($_COOKIE)) and perhaps session values, anything you feel is useful to analyse and look to see what you get.
    Richard Davey

    Launchcode
    PHP Security Guide. Think your scripts are secure? Think again.

  3. #3
    <? echo "Kick me"; ?> petesmc's Avatar
    Join Date
    Nov 2000
    Location
    Hong Kong
    Posts
    1,508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just wanted to mention, you have a security risk, in that you are not checking your passwords/usernames for quotes (' and "), hence a mysql injection attack could be executed. Please use addslashes() on your password/username.

    -Pete

  4. #4
    SitePoint Wizard swdev's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Better still, use mysql_real_escape_string after you have cheked to see whether magic_quotes_gpc is on or of and run stripslashes as appropriate
    Last edited by swdev; Jan 8, 2005 at 19:41. Reason: typo

  5. #5
    SitePoint Zealot skipdawg95's Avatar
    Join Date
    Oct 2004
    Location
    Strasburg, VA
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Would something like this work?

    PHP Code:
    if (isset ($_POST['userName'])) {
    // Quote variable to make safe
        
    function quote_smart($value) {
            
    // Stripslashes
            
    if (get_magic_quotes_gpc()) {
                
    $value stripslashes($value);
            }
            
    // Quote if not integer
            
    if (!is_numeric($value)) {
            
    $value "'" mysqli_real_escape_string($value) . "'";
            }
            return 
    $value;
            }
        
    quote_smart($_POST['userName']);
        
    quote_smart($_POST['password']);
        
    //Run query.
        
    if ($user mysqli_query($conn"SELECT * FROM userInfo WHERE userName = '$_POST[userName]' AND password = '$_POST[password]' AND active = '1'") or die ("Error performing mysql query!")) {
        
    $number mysqli_num_rows($user); 

  6. #6
    SitePoint Wizard swdev's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Almost

    1. I would define the quote_smart function in a spearate file and include it when necessary.
    2. quote_smart returns the changed value which you need to store. So your calling code should be
      PHP Code:
       $_POST['username'] = quote_smart($_POST['username']); 
    3. I would pass a second parameter called, say, Type to the quot_smart function. This parameter would be one of 'string', 'int' or 'float'. That way, withing the function, you could call the appropriate conversion function, rather than relying on
      the fact that if a string looks like a number then it must be a number.
    4. Passowrds. It looks like you are storing clear text passwords in the database. I would encrypt the password using something like the MySQL PASSWORD function, of a PHP function like md5 or sha1


    Hope this helps

  7. #7
    SitePoint Zealot skipdawg95's Avatar
    Join Date
    Oct 2004
    Location
    Strasburg, VA
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You lost me on #4.

  8. #8
    SitePoint Zealot skipdawg95's Avatar
    Join Date
    Oct 2004
    Location
    Strasburg, VA
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Opps, I mean #3. I got the password part. I'm just using clear text to work with on a stand alone computer. The password encryption is my next step.

  9. #9
    SitePoint Wizard swdev's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What meant by point 3 was something like this

    PHP Code:
      
      
    function QuoteSmart($Value$Type)
      {
        
    // remove extraneous slashes if necessary
        
    if (=== get_magic_quotes_gpc())
        {
          
    $Value stripslashes($Value);
        }
      
      
        
    // convert value to appropriate type
        
    switch($Type)
        {
          case 
    'string':
            
    $value '\'' mysql_real_escape_string($Value) . '\'';
            break;
      
          case 
    'int':
            
    $value =  intval($Value);
            break;
      
          case 
    'float':
            
    $value =  floatval($Value);
            break;
      
          default:
            
    $Value '';
            break;
        }
      
      
    // return sanitised value
      
    return $Value;
      }
      
      
      
    // Call SmartQuote like this
      
    $_POST['username'] = QuoteSmart($_POST['username'], 'string'); 
    The reason I would pass in the type of vaue to the SmartQuote function, is that I, as the developer, know exactly what type of item this value is.
    With your original code, if the value was '4e4' you would treat this as an integer. This may be correct, but it may be a string. With my code, the developer tells the code what to do with the value rather than the code having to guess at what to do.

    I hope this makes it a little clearer.

  10. #10
    SitePoint Zealot skipdawg95's Avatar
    Join Date
    Oct 2004
    Location
    Strasburg, VA
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Got it! Thanks for the help! I'm still in the learning stages, but it's all starting to come together now.

  11. #11
    SitePoint Wizard swdev's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Glad it is all beginning to make sense.

    Keep at it, and keep asking questions .

  12. #12
    SitePoint Zealot skipdawg95's Avatar
    Join Date
    Oct 2004
    Location
    Strasburg, VA
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Now that you mention it, I'm hitting a wall. I took your code to play with it and I'm having problems with it. Here's what I did:

    PHP Code:
    function QuoteSmart($Value$Type) {
        
    //Remove extraneous slashes if necessary
            
    if (=== get_magic_quotes_gpc()) {
                
    $Value stripslashes($Value);
                }
            
    // convert value to appropriate type
            
    switch($Type) {
                case 
    'string':
                    
    $value =  '\'' mysqli_real_escape_string($conn$Value) . '\'';
                    break;
                case 
    'int':
                    
    $value =  intval($Value);
                    break;
                case 
    'float':
                    
    $value =  floatval($Value);
                    break;
                default:
                    
    $Value '';
                    break;
            }
        
    // return sanitised value
        
    return $Value;
    }
    $userName skipdawg95;
    QuoteSmart ($userName'string');
    print 
    $userName
    This is the error I'm getting:

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\Program Files\Apache Group\Apache2\htdocs\test.php on line 20

  13. #13
    SitePoint Wizard swdev's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah - are you using PHP 5?

    The function needs to be passed the active conection, like this

    PHP Code:
      function QuoteSmart($Value$Type$DBConnection) {
          
    //Remove extraneous slashes if necessary
              
    if (=== get_magic_quotes_gpc()) {
                  
    $Value stripslashes($Value);
                  }
              
    // convert value to appropriate type
              
    switch($Type) {
                  case 
    'string':
                  
    $value '\'' mysqli_real_escape_string($DBConnection$Value) . '\'';
                      break;
                  case 
    'int':
                      
    $value =  intval($Value);
                      break;
                  case 
    'float':
                      
    $value =  floatval($Value);
                      break;
                  default:
                      
    $Value '';
                      break;
              }
          
    // return sanitised value
          
    return $Value;
      }
      
      
    // assume $conn is the connection id of the active connection
      
    $userName skipdawg95;
      
    QuoteSmart ($userName'string'$conn);
      echo 
    $userName

  14. #14
    SitePoint Zealot skipdawg95's Avatar
    Join Date
    Oct 2004
    Location
    Strasburg, VA
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You rock! Thanks...it worked like a charm.


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
  •