473,893 Members | 1,663 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to secure the pages of php by using session

25 New Member
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
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include 'functions.php';
  3. session_start();
  4. if($_SESSION["a"]!=1)
  5. {
  6. header("location:index.php");    
  7.  
  8. }

And this is my login screen.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include 'functions.php';
  3.  
  4.  
  5. if ($_POST["login"])
  6. {
  7.     global $username;
  8.     $username = $_POST['username'];
  9.     $password = $_POST['password'];
  10.     $rememberme = $_POST['rememberme'];
  11.  
  12.  
  13.     if($username&&$password)
  14.     {
  15.  
  16.     $login = mysql_query("SELECT * FROM usersystem WHERE username='$username'");
  17.     while ($row = mysql_fetch_assoc($login))
  18.     {
  19.         $db_password =  $row['userpass'];
  20.         if(md5($password)==$db_password)
  21.         $loginok = TRUE;
  22.     else
  23.         $loginok = FALSE;
  24.  
  25.         if ($loginok==TRUE)
  26.         {
  27.             $_SESSION["a"] = 1; 
  28.             if ($rememberme=="on")
  29.             setcookie("username", $username, time()+7200);
  30.         else if ($rememberme=="")
  31.         $_SESSION['username']== $username;
  32.         $_SESSION['username'] =$_POST['username'];
  33.  
  34.         header("Location: redirectpage.php");
  35.         exit();
  36.  
  37.         }
  38.  
  39.     }
  40.  
  41.  
  42.     }
  43.     else
  44.     die("Please enter a username and password");
  45. }
  46.  
  47. ?>
  48.  
Jan 26 '10 #1
9 3274
shabinesh
61 New Member
I understand what you are trying to do, but what is your question??
Jan 27 '10 #2
RomeoX
25 New Member
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.
Jan 27 '10 #3
shabinesh
61 New Member
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.
Jan 27 '10 #4
Atli
5,058 Recognized Expert Expert
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:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. if(isset($_POST['name'], $_POST['password']))  
  3. {
  4.     $name = mysql_real_escape_string($_POST['name']);
  5.     $pwd_hash = hash('sha1', $_POST['password']);
  6.  
  7.     $sql = "SELECT `id` FROM `user` 
  8.             WHERE (`name` = '{$name}')
  9.             AND   (`password` = '{$pwd_hash}')";
  10.  
  11.     $result = mysql_query($sql) or trigger_error(mysql_error(), E_ERROR);
  12.     if(mysql_num_rows($result) == 1) 
  13.     {
  14.         $row = mysql_fetch_assoc($sql);
  15.  
  16.         session_start();
  17.         $_SESSION['user']['id'] = $row['id'];
  18.         $_SESSION['user']['name'] = $name;
  19.  
  20.         if(isset($_POST['remember_me']))
  21.         {
  22.             // Create a "secure" hash that can be used to verify the user
  23.             // login later.
  24.             $cookie_hash = hash('sha512', $row['id'] . $name . $pwd_hash);
  25.  
  26.             // Create two cookies. One to store the user ID (so it can be
  27.             // retrieved later to verify the hash), and one for the hash.
  28.             set_cookie('user_login_id', $row['id'], time() + (3600 * 24 * 30));
  29.             set_cookie('user_login_hash', $cookie_hash, time() + (3600 * 24 * 30));
  30.         }
  31.     }
  32.     else
  33.     {
  34.         echo "Login failed. Please try again!";
  35.     }
  36. }
  37. else
  38. {
  39.     echo "Username and/or password were not passed.";
  40. }
  41. ?>
You could use this function to verify if the user is logged in:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. function isUserLoggedIn() 
  3. {
  4.     // Check if the user session already exists.
  5.     if(isset($_SESSION['user'])) 
  6.     {
  7.         return true;
  8.     }
  9.  
  10.     // Look for a cookie from the "remeber me" feature.
  11.     else if(isset($_COOKIE['user_login_id'], $_COOKIE['user_login_hash'])) 
  12.     {
  13.         // Verify that the cookie data is valid
  14.         $id = (int)$_COOKIE['user_login_id'];
  15.         $hash = (string)$_COOKIE['user_login_hash'];
  16.  
  17.         $sql = "SELECT `name`, `password` 
  18.                 FROM `user` 
  19.                 WHERE (`id` = {$id})";
  20.         $result = mysql_query($sql) or trigger_error(mysql_error(), E_ERROR);
  21.         if(mysql_num_rows($result) == 1) 
  22.         {
  23.             $row = mysql_fetch_assoc($sql);
  24.             $real_hash = hash('sha512', $id . $row['name'] . $row['password']);
  25.  
  26.             if($real_hash == $hash) 
  27.             {
  28.                 // Log the user in, so the cookie does not need to be
  29.                 // checked on every page.
  30.                 $_SESSION['user']['id'] = $id;
  31.                 $_SESSION['user']['name'] = $row['name'];
  32.  
  33.                 return true;
  34.             }
  35.         }
  36.     }
  37.  
  38.     // No login method available. User is not logged in.
  39.     return false;
  40. }
  41. ?>
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.
Jan 27 '10 #5
johny10151981
1,059 Top Contributor
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
Jan 27 '10 #6
kovik
1,044 Recognized Expert Top Contributor
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.
Jan 27 '10 #7
RomeoX
25 New Member
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
Jan 27 '10 #8
Atli
5,058 Recognized Expert Expert
@kovik
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

@RomeoX
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 ;-)
Jan 27 '10 #9
itsmenarwal
20 New Member
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
Feb 2 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

18
2482
by: | last post by:
Please help. After a number of wrong turns and experiments I need advice on login management system to secure our web pages without inconveniencing our visitors or our internal staff. What I need: A system whereby the user only has to register ONCE and he will have automatic entry to ANY page without havinto to RE-LOGIN even if he comes in
1
1610
by: Astra | last post by:
Hi All I know this probably sounds like a newbie question, but I was under the impression that secure pages (https) don't appear in the history/address bar history list - this appears to be incorrect? Should I really be putting some form of expiry command at the head of each of these pages if I don't want casual users to see them? I use Classic ASP so is it better to use a command via this lang or the old
3
14053
by: Pooja Renukdas | last post by:
Hello, I have this web site where only two pages have to be secure pages and I need to call them using https, but since I have my development server and my production web server, I dont want to enter the absolute url like response.redirect("https://myProductionServer.com/SecurePage.aspx"), because when Im working in the development server I would have to change it back and forth everytime. Is there an easy way to do this without having...
7
3030
by: Seth | last post by:
I have noticed that the id of my session object changes when I switch from a non-secure to a secure connection. What I'm trying to do: I have a cookie that is built on the non-secure side of things. What I need to do is to switch to a secure connection and then later on while still in that secure connection delete the cookie that was created on the non- secure side. I need to do this because I can not reference the non-secure cookie...
0
1336
by: Daniel Malcolm | last post by:
Hi I have a site where I would like some pages to be accessed via SSL (login and payment etc) and others via regular http. However I'm not sure whether Session state can be maintained between the 2 protocols. We have SSL set up on the site so that it can be accessed via the same domain: http://www.mydomain.com/login.aspx
5
2183
by: Joe | last post by:
I have an application which runs in a non-secure environment. I also have an application that runs in a secure environment (both on the same machine). Is there any way to share the session data for this? Most of the site allows the user to add things to a cart (non-secure), once they choose to check-out, I need this information which was stored in the session to be read by the payment page(secured). Hope this makes sense. It's probably...
6
3009
by: Notgiven | last post by:
I am considering a large project and they currently use LDAP on MS platform. It would be moved to a LAMP platform. OpenLDAP is an option though I have not used it before. I do feel fairly confortable with my ability to use SESSIONS for authentication and access control. Would it better to learn and use LDAP or can you REALLY have just as secure authentication and access control using Sessions? Thanks for your thoughts and experience.
14
4934
by: knal | last post by:
Hi there, I'm looking for a secure login script for a sort-of-community site... (PHP, MySQL, sessions, or maybe something else ... ) I know there are a lot of scripts out there, but none of them really seem secure, or have other kind of flaws (like IP based login etc.). Why i'm asking here, is because there's experience out there, and i hope experience can tell me what my best shot is. I'm aware that i will very probably have to do...
8
2878
by: Harris Kosmidhs | last post by:
Hello, while I'm developing sites for some time I never coded a login form with security in mind. I was wondering what guidelines there are. For my point of view I'm thinking of using md5 passwords (it's an one way function right?) in db. Is this a correct approach?
1
1953
by: bizt | last post by:
Hi, I have a webpage where Im creating AJAX type requests by loading dynamic pages containg JavaScript into hidden iFrames. The reason I am opting for this method over XmlHttpRequest object requests is because I wish for some of my requests to be over a secure https:// connection and other not so private requests to be made over http:// .. using XmlHttpRequest I am unable to make requests between two domains http/ https from the one...
0
9985
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11244
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9646
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8022
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7173
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6066
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4280
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3289
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.