how to secure the pages of php by using session

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RomeoX
    New Member
    • Jan 2010
    • 25

    how to secure the pages of php by using session

    Hi there,

    I have a question related to Session. I made a login screen and all pages except than the login page should be secure, so no one can access to any page unless access from the main login page, so I did this coding but even if someone checked the option of "Remember Me" and if he/she closed the browser and come back again he can enter access any pages because the Cookies is still available because I made it here for 2 hours so after that no one can access the page, and I made another Logout so if someone press it it will remove the cookies so has to login again. So any solution for the problem.

    This code I putted in my important pages
    Code:
    <?php
    include 'functions.php';
    session_start();
    if($_SESSION["a"]!=1)
    {
    header("location:index.php");	
    	
    }

    And this is my login screen.
    Code:
    <?php
    include 'functions.php';
    
    
    if ($_POST["login"])
    {
    	global $username;
    	$username = $_POST['username'];
    	$password = $_POST['password'];
    	$rememberme = $_POST['rememberme'];
    
    
    	if($username&&$password)
    	{
    
    	$login = mysql_query("SELECT * FROM usersystem WHERE username='$username'");
    	while ($row = mysql_fetch_assoc($login))
    	{
    		$db_password =  $row['userpass'];
    		if(md5($password)==$db_password)
    		$loginok = TRUE;
    	else
    		$loginok = FALSE;
    		
    		if ($loginok==TRUE)
    		{
    			$_SESSION["a"] = 1; 
    			if ($rememberme=="on")
    			setcookie("username", $username, time()+7200);
    		else if ($rememberme=="")
    		$_SESSION['username']== $username;
    		$_SESSION['username'] =$_POST['username'];
    	
    		header("Location: redirectpage.php");
    		exit();
    
    		}
    
    	}
    
    
    	}
    	else
    	die("Please enter a username and password");
    }
    
    ?>
  • shabinesh
    New Member
    • Jan 2007
    • 61

    #2
    I understand what you are trying to do, but what is your question??

    Comment

    • RomeoX
      New Member
      • Jan 2010
      • 25

      #3
      I want when I check the "Remeber Me" I still able when I close the browser I can still to access any page, not returning me again to the first page of login screen. I hope it's clear. Thanks for your reply I appreciate your passing to my thread.

      Comment

      • shabinesh
        New Member
        • Jan 2007
        • 61

        #4
        okay!! usually 'remember me' option is used to store the data in the client. Assuming you are storing the username and password, the next time you open your page the username and password is already filled in rather no need to type it again.

        Now, when you close the browser, the session is destroyed, the next time you may have to login again to access your pages.

        I think your program works correctly.

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          Hey.

          To make a secure "remember me" feature, you need to create a cookie that contains data that only the logged in user could know. Normally, this is some sort of a hash compiled from the user login/personal data.

          The general procedure is, at the top of every page:
          • Check if the user is already logged in, by checking if the session is set.
          • If he is not, check if a "remember me" cookie is set.
          • If it is, verify that the information in the cookie is correct, and log the user in if it is.
          • Otherwise, if the page is meant to be secure, redirect the user to the login page.


          For example, if your login routine looked something like this:
          [code=php]<?php
          if(isset($_POST['name'], $_POST['password']))
          {
          $name = mysql_real_esca pe_string($_POS T['name']);
          $pwd_hash = hash('sha1', $_POST['password']);

          $sql = "SELECT `id` FROM `user`
          WHERE (`name` = '{$name}')
          AND (`password` = '{$pwd_hash}')" ;

          $result = mysql_query($sq l) or trigger_error(m ysql_error(), E_ERROR);
          if(mysql_num_ro ws($result) == 1)
          {
          $row = mysql_fetch_ass oc($sql);

          session_start() ;
          $_SESSION['user']['id'] = $row['id'];
          $_SESSION['user']['name'] = $name;

          if(isset($_POST['remember_me']))
          {
          // Create a "secure" hash that can be used to verify the user
          // login later.
          $cookie_hash = hash('sha512', $row['id'] . $name . $pwd_hash);

          // Create two cookies. One to store the user ID (so it can be
          // retrieved later to verify the hash), and one for the hash.
          set_cookie('use r_login_id', $row['id'], time() + (3600 * 24 * 30));
          set_cookie('use r_login_hash', $cookie_hash, time() + (3600 * 24 * 30));
          }
          }
          else
          {
          echo "Login failed. Please try again!";
          }
          }
          else
          {
          echo "Username and/or password were not passed.";
          }
          ?>[/code]

          You could use this function to verify if the user is logged in:
          [code=php]<?php
          function isUserLoggedIn( )
          {
          // Check if the user session already exists.
          if(isset($_SESS ION['user']))
          {
          return true;
          }

          // Look for a cookie from the "remeber me" feature.
          else if(isset($_COOK IE['user_login_id'], $_COOKIE['user_login_has h']))
          {
          // Verify that the cookie data is valid
          $id = (int)$_COOKIE['user_login_id'];
          $hash = (string)$_COOKI E['user_login_has h'];

          $sql = "SELECT `name`, `password`
          FROM `user`
          WHERE (`id` = {$id})";
          $result = mysql_query($sq l) or trigger_error(m ysql_error(), E_ERROR);
          if(mysql_num_ro ws($result) == 1)
          {
          $row = mysql_fetch_ass oc($sql);
          $real_hash = hash('sha512', $id . $row['name'] . $row['password']);

          if($real_hash == $hash)
          {
          // Log the user in, so the cookie does not need to be
          // checked on every page.
          $_SESSION['user']['id'] = $id;
          $_SESSION['user']['name'] = $row['name'];

          return true;
          }
          }
          }

          // No login method available. User is not logged in.
          return false;
          }
          ?>[/code]

          If would recommend making the cookie has a bit more complex though, by adding other data to the hash. The more complex and unpredictable, the better.

          Comment

          • johny10151981
            Top Contributor
            • Jan 2010
            • 1059

            #6
            hello RomeoX,
            Session is get created in server. The policy you have used is simple

            1. check if the user is under session
            2. if it is yes let the user access the desired page
            3. else you redirect the user to log in page.

            The question is how long session is valid?
            The answer is inserted in the php.ini
            by default it is 20 munites. so, in general, after logging in a user will be able to use the same session(without knowing ;) ) for 20 munites. But if you dont update session in server site the user will be logged out even if he was using continuously.

            after first log in, if a user close its browser and then reopen it, he may work using the previous session. because he did close his browser but he didnt turned off the session (cause session is working in the server).

            I am not sure if this is possible,
            Can you add a javascript code that will work on browser closing. Say if a browser close events occur simply create a AJAX request with sign out information. It may help.

            But in the current browser like firefox or ie. If you close entire browser and reopen it, you actually wont get the previous session. so I guess you can tell me what browser you are using.

            Best Regards,
            Johny

            Comment

            • kovik
              Recognized Expert Top Contributor
              • Jun 2007
              • 1044

              #7
              Well, "Remmber Me" and "Stay Logged In" are 2 different things.

              "Remember Me" just saves their username. This can be done easily by simply setting a "username" variable in their cookies and automatically loading it into the username field.

              However, the "Stay Logged In" functionality is more in-depth. You don't want to use a pre-compiled hash as ~Atli suggested. If anyone were to discover this hash (i.e. a hacker, a friend of the user who is experienced with cookie manipulation, etc.), they could copy it and use it. You do want to use a similar method, but you'll want to make it different every time that they log in.

              Basically, you'll want to have an extra database column in your user's table that saves their current "auto_login " code. Any time that they visit your website and they are not logged in, check the "auto_login " code from their cookie to the "auto_login " code in the database. If they are the same, log the user in and change the code to a new, randomly generated code and save it in both locations. If the code is invalid, simply delete the cookie.

              I've heard of programmers wanting to penalize people with incorrect "auto_lgin" codes in their cookies, assuming it was a failed hacking attempt, but what if you log in from work, then again from home? Of course, if you wanted to, you could save multiple "auto_login " codes, but that starts to whittle down your security measures.

              Comment

              • RomeoX
                New Member
                • Jan 2010
                • 25

                #8
                Thanks a lot to everyone provide me a suggestions. Actually I use IE8.


                Actually I don't know how I can make an auto login code so it will make comparative to cookies, if you have something hopefully you post it here.

                Anyway, Thanks to you

                Comment

                • Atli
                  Recognized Expert Expert
                  • Nov 2006
                  • 5062

                  #9
                  Originally posted by kovik
                  However, the "Stay Logged In" functionality is more in-depth. You don't want to use a pre-compiled hash as ~Atli suggested.
                  [...]
                  Basically, you'll want to have an extra database column in your user's table that saves their current "auto_login " code...
                  Your right. That is a much better method. It costs you a bit of space, but is a LOT more secure... Can't believe I didn't think of that xD

                  Originally posted by RomeoX
                  Actually I use IE8.
                  The worst mistake a web-developer makes... or anybody, for that matter.

                  Get Firefox or Chrome. It's better for you, AND it's better for everybody else ;-)

                  Comment

                  • itsmenarwal
                    New Member
                    • Jan 2010
                    • 20

                    #10
                    But how to check login status and what values we should send to database..Plz give example with code so that we can understand..I will be thankfull to you

                    Comment

                    Working...