Web Analytics Made Easy -
StatCounter Setting a secure cookie? - CodingForum

Announcement

Collapse
No announcement yet.

Setting a secure cookie?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Resolved Setting a secure cookie?

    Okay, so i'm fairly new to coding PHP websites from scratch (have used template codes, and tweaked them around a little for awhile now)
    So today me and my friend started out own website, and so far i have these webpages:

    login.php (just the form to submit data to checklogin.php)

    checklogin.php (contains the check between mysql and entered data and logs in if its right.

    Register.php (Again, contains the form to submit data to checkregister.php)

    checkregister.php (contains a check to see whether the username or e-mail already exists, checks to see if both passwords entered in register.php match, and after this submits it to the mysql database.)

    logout.php (just contains Session_Destroy(); )

    and page1.php (just a page saying password correct, you get re-directed here from checklogin.php ofc if your password is correct.)

    Okay, so i've added into checklogin.php:
    PHP Code:
    $expiry time() + 172800;
    setcookie"userlogin"'$username'$expiry ); 
    This shoudl set a cookie called userlogin, with the data from the variable $username (which is set by $_POST['username'])

    So basically i want page 1 to actually say:
    Welcome (their username here), (their E-mail address here)

    so i thought the only way to do that is through setting a cookie right?
    and to get their e-mail address i was going to do it, by matching their username in their database and then reading this from the database (i can do this myself, it's fairly straight forward)

    But then it leaves a vulnerability then, if a person was to fake a cookie of a different user, they would then be able to get their e-mail address too, because the PHP code is set to match a e-mail address with the name stored in the cookie, and then display it.

    I hope this all makes sense to you so far...

    So my question is, how would i stop this from being able to be done... (getting an account's e-mail address from spoofing a cookie)

    I'll happily answer any questions you have got about the information of my pages etc.
    Thanks .
    Last edited by philip_l_g; Apr 12, 2009, 02:18 PM. Reason: Got it working.

  • #2
    It is not good idea to make any operation based on the data which is located in cookie because it could be changed within 5 min no need for special knowledge.

    So the best idea is to keep all that information in cookies (email and user name) in that case there are there you can show and you do not care if someone will change them (but again you should not relay on them).

    BUT if you still want to relay on information, for example lets say you want to check that user have passed authentication, in that case you need to keep such variable (for example userLogin = true) in session which is kept on server site.

    Comment


    • #3
      Originally posted by PHP6 View Post
      It is not good idea to make any operation based on the data which is located in cookie because it could be changed within 5 min no need for special knowledge.

      So the best idea is to keep all that information in cookies (email and user name) in that case there are there you can show and you do not care if someone will change them (but again you should not relay on them).

      BUT if you still want to relay on information, for example lets say you want to check that user have passed authentication, in that case you need to keep such variable (for example userLogin = true) in session which is kept on server site.

      Ahh thanks, i didnt know about the variable being able to be kept in the session, could you post a simple example of how its done? i'll research more on google in the mean time .

      Edit:

      Thanks, i'm just reading up on sessions right now, if anyone else is looking for help with sessions, here's a helpful tutorial:
      http://www.tizag.com/phpT/phpsessions.php
      Last edited by philip_l_g; Apr 11, 2009, 02:45 PM.

      Comment


      • #4
        Since that is your first project where you are going to implement authentication I think it will be nice to warn you that you should not keep passwords in database or anywhere else open (that was the mistake I made when I was doing my first authentication ). Instead of saving them open make their MD5 values and save that string.

        Later when you will need to check password MD5 the password which user will enter and match the values. That method will prevent your passwords to be stolen by someone else even if they will get access to database or storage in general (any string has unique MD5 value and MD5 cannot be converted back to string)

        Comment


        • #5
          Originally posted by PHP6 View Post
          Since that is your first project where you are going to implement authentication I think it will be nice to warn you that you should not keep passwords in database or anywhere else open (that was the mistake I made when I was doing my first authentication ). Instead of saving them open make their MD5 values and save that string.

          Later when you will need to check password MD5 the password which user will enter and match the values. That method will prevent your passwords to be stolen by someone else even if they will get access to database or storage in general (any string has unique MD5 value and MD5 cannot be converted back to string)
          Already on it :P, i set it up on registration, t
          it does MD5 encryption on the password, so it enters the database as MD5, and then, on the login, it converts the submitted data to MD5 to check against the database. I hope that's what you mean :P?
          Also, i have a new problem:

          When i use this query to select the ID from the database, given the username:
          PHP Code:
          $sql="SELECT 'id' FROM $tbl_name WHERE 'username' = $_SESSION[myusername]";
          $result=mysql_query($sql); 
          so this query SHOULD be searching the database for the current username logged in, and then retrieve the value under the ID column for that username if you understand what i mean? instead it returns either nothing, or Resource id 2 i dont understand why it does this, anyone got an idea?

          Comment


          • #6
            don't forget to regenerate session id (cookie) after login

            PHP Code:
            <?php session_regenerate_id(); ?>
            that'll stop whats known as session fixation...

            also monitor the ip/agentstring

            if one of them changes from a page to page, log them out and terminate session.... also give a notification of why it's happened (don't ban them though... because there are tools to change agent string, and a lot of people do this for their own testing purposes, and well ip's can change typicaly not in a session though)
            Last edited by primefalcon; Apr 11, 2009, 08:33 PM.
            get up to 32 gigaytes free cloud storage at Dropbox

            For Tips on Runescape, Visit Marlaine's Musings

            Comment


            • #7
              No comments
              PHP Code:
              $sql="SELECT 'id' FROM $tbl_name WHERE 'username' = {$_SESSION[myusername]}";
              // check if our query was successful
              if ($result $result=mysql_query($sql))
                
              // check if there is any result and it should be equal to 1 ;)
                
              if (($amount = @mysql_num_rows($result))and($amount == 1)) {
                  
              $fetch mysql_fetch_array($resultMYSQL_ASSOC);
                  
              $userId $fetch['id'];
                } 
              I hope that's what you mean :P?
              You are absolutely right, good job!!!

              Comment


              • #8
                Originally posted by PHP6 View Post
                No comments
                PHP Code:
                $sql="SELECT 'id' FROM $tbl_name WHERE 'username' = {$_SESSION[myusername]}";
                // check if our query was successful
                if ($result $result=mysql_query($sql))
                  
                // check if there is any result and it should be equal to 1 ;)
                  
                if (($amount = @mysql_num_rows($result))and($amount == 1)) {
                    
                $fetch mysql_fetch_array($resultMYSQL_ASSOC);
                    
                $userId $fetch['id'];
                  } 

                You are absolutely right, good job!!!
                Thank you very much, i couldnt understand why it wouldnt display the ID, you've been a great help, thanks .


                EDIT:

                Hmm, i'm still having an error with it fetching the id, it just shows up nothing, using the query you posted. this is the part i've wrote that should be displaying the information:

                PHP Code:
                Echo "Welcome $_SESSION[myusername], your UserID is $userId."
                Last edited by philip_l_g; Apr 12, 2009, 06:58 AM.

                Comment


                • #9
                  Originally posted by philip_l_g View Post
                  Hmm, i'm still having an error with it fetching the id, it just shows up nothing, using the query you posted. this is the part i've wrote that should be displaying the information:

                  PHP Code:
                  Echo "Welcome $_SESSION[myusername], your UserID is $userId."
                  Ok, now I will show you the sample how you could solve such problem in the future and save your time waiting the replay on any forum When you have some kind of problem with script you need to try analyze everything very carefully even the part of the code which seems to be 100% correct. You should take in account that if you have different result that means there is some error and it could be any, even simple missing comma

                  In your case you need to test following to identify where you have error:

                  1) Check that your quest is well formatted... right after $sql="SELECT... add following line var_dump($sql); or echo $sql; that will output the result so you could visually check that variable contain correct and well formatted SQL request.

                  2) Case you variable $sql seems to be correct than use phpMyAdmin or if you prefer command line to execute that query by your own and see if you get expected result

                  3) Case first two steps where correct, now you need to check that $userId get the correct value... to do so add the same var_dump or echo command after IF statement

                  based on the result you could identify where the problem is and start searching the solution

                  p.s. and always post what error you get from PHP so we could found possible bug. Try to place $_SESSION in {} and add '' because you are accessing the element of an array, so you will have
                  PHP Code:
                  Echo "Welcome {$_SESSION['myusername']}, your UserID is $userId."
                  Last edited by PHP6; Apr 12, 2009, 07:42 AM.

                  Comment


                  • #10
                    okay, i think the problem is with the format of the query, as it receives this error when i try and execute it with PHPmyAdmin:
                    #1054 - Unknown column 'phil' in 'where clause'
                    where it says phil, this would be {$_SESSION['myusername']}. I've had a little play around with it, but i always receive the 'where clause' part, i dont understand what this actually means :S?

                    Comment


                    • #11
                      Try to enclose user name with "" and before you will execute it print it out and post it here so we can see what is going on.
                      PHP Code:
                      $sql="SELECT 'id' FROM $tbl_name WHERE 'username' = \"{$_SESSION[myusername]}\""

                      Comment


                      • #12
                        Originally posted by PHP6 View Post
                        Try to enclose user name with "" and before you will execute it print it out and post it here so we can see what is going on.
                        PHP Code:
                        $sql="SELECT 'id' FROM $tbl_name WHERE 'username' = \"{$_SESSION[myusername]}\""
                        Well it doesnt receive an error, just display 0 rows, which doesnt make sense :S... as there should be a result :S.

                        Here's the query that creates:
                        Code:
                        SELECT 'id' FROM members WHERE 'username' = "phil"
                        i've tried putting 's around the members, and still nothing, it just doesnt seem to think theres a match with the username i think :S?

                        Edit:
                        Aha! i successfully got it working, i used this in the php file to get the result to work:
                        PHP Code:
                        $sql="SELECT `id` FROM `members` WHERE `username` = '{$_SESSION[myusername]}'"
                        No idea why it worked, i think it has something to do with the fact i actually typed in the table name, i will test it out using
                        PHP Code:
                        `$tbl_name
                        in place of just `members` now, but im guessing it works.

                        EDIT:
                        Yep, works fine. Thanks very much for your help PHP6!
                        Last edited by philip_l_g; Apr 12, 2009, 02:18 PM.

                        Comment

                        Working...
                        X