PHP - Sessions And Cookies - Logged In Until Users Sign Out.
I am trying to build my own custom login script.
What I am trying to achieve is once a user has logged in depending on wether they have checked the keep me logged in checkbox they have two options. If they haven't checked it then it creates session variables only, and if they have checked it it also creates cookie variable as well as the session variables. If they then close their browser / tab without logging out and then revisit the site they will get redirected to login page because the active session variable is no longer there. As soon as they land on the loggin page, it automatically checks for the cookie variable and if it exists, it uses it to login and redirect them automatically. However the problem that I am facing is that the session variable is still being trashed after a default amount of idle time and forcing a login. My goal is that the user shouldn't have to re-login unless they have either clicked the logout button. Can someone please have a look through my solution and advise me as to wether this is the correct method that I am implementing, if there is an easier way to achieve what I want, and is this a secure way to handle user logins. Thanks in advance. Andrew Here is the check code I have placed at the top of each admin page. Code: [Select] <?php session_start(); $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $uid = $_SESSION['uid']; if (!isset($uid)) { header('location:login.php?redirect='.$url); exit(); } ?> Next we have the code for the login.php file. Code: [Select] <?php include ('functions.php'); ?> <?php get_header('login'); ?> <div id="login-result"> <?php connect(); $redirect = htmlspecialchars(mysql_real_escape_string(addslashes($_GET['redirect']))); if(isset($_COOKIE['remembered'])){ $username = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['username']))); $password = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['remembered']['password']))); $sql = "SELECT * FROM usersT WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); $row = mysql_fetch_array($result); $uid = $row['uid']; $fname = $row['firstname']; $lname = $row['lastname']; $role = $row['role']; if($count==1){ $sql2 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result2 = mysql_query($sql2); if($result2){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } else if (isset($_POST['admin_login'])){ if(isset($_POST["username"]) && isset($_POST["password"])){ $username_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["username"]))); $password_p = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["password"]))); $psw = md5($password_p); $sql3 = "SELECT * FROM usersT WHERE username='$username_p' AND password='$psw'"; $result3 = mysql_query($sql3); $count3 = mysql_num_rows($result3); $row3 = mysql_fetch_array($result3); $uid = $row3['uid']; $fname = $row3['firstname']; $lname = $row3['lastname']; $role = $row3['role']; if($count3==1){ $sql4 = "UPDATE usersT SET status = '1' WHERE uid = '$uid'"; $result4 = mysql_query($sql4); if($result4){ session_register("uid"); session_register("uname"); session_register("ulevel"); $_SESSION["uid"] = $uid; $_SESSION["uname"] = $fname; $_SESSION["ufullname"] = $fname . " " .$lname; $_SESSION["urole"] = $role; $home = get_option('home'); if(isset($_POST['remember'])) { setcookie("remembered[username]", $username, time() + 86400 * 365 * 2); setcookie("remembered[password]", $psw, time() + 86400 * 365 * 2); } if(!empty($redirect)) { header( 'Location: '. $redirect ) ; exit(); } else { header( $home ) ; exit(); } } } else { echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>"; } } } ?> </div><!-- / login-results --> <div id="login" class="rounded5 shadow"> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label for="username">Username<br> <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label> </p> <p> <label for="password">Password<br> <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" /></label> </p> <p class="submit"> Keep me logged in<input type="checkbox" name="remember" id="remember" /><br /><br /><a href="" class="left">Lost your password?</a> <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" /> </p> <div class="cleaner"></div><!-- / cleaner --> </form> </div><!-- / login--> <?php get_footer('login'); ?> Finally here is the code I am using for the logout.php page. Code: [Select] <?php session_start(); include ('functions.php'); connect(); $uid = mysql_real_escape_string($_SESSION['uid']); $sql = "UPDATE usersT SET status = '0' WHERE uid = '$uid'"; $result = mysql_query($sql); if($result) { session_unset(); session_destroy(); if(isset($_COOKIE['remembered'])){ setcookie("remembered[username]", $username, time() - 3600); setcookie("remembered[password]", $psw, time() - 3600); header("location: login.php"); } exit(); } else { echo "You couldn't be logged out at this time."; } ?> Similar TutorialsPlease help me out with sessions . I m new to this topic.
Sites such as this one often show the logged on users and guests.
I have no reason to need to do so, but am curious on how this is accomplished.
For users, yes, you've authenticated them and logged them on regardless of IP address, but how do you know they didn't just close their browser?
For guests, are they just using IP address? And still, how do you know when they leave?
PS. How should I include an image in a post like I did? What I did was first attach a file, and then edit the post to include that file as an image. Couldn't seem to include an image off my local PC. Not a better way?
Attached Files
Capture.PNG 4.13KB
0 downloads What are the different ways you can keep a User "logged in"? From what I *vaguely* recall from a year or two ago when I read a whole hoard of PHP books, you commonly use cookies and sessions. But I'm asking this more from an OOP standpoint than a PHP standpoint. Let's say I have a User record in my database, and a User comes along and attempts to log in. In OOP terms, I would think you'd call some class to help log them in, and upon successfully logging in, you would "load" the User object into memory and set the "LoggedIn" field to "True". Then as long as that field was set in their object, they could surf all over the place and do things like change their account and buy things. Is that how you would do it in OOP? TomTees Hi all, Does anyone know of an effective way of find out whether a user is still logged in and they haven't left? Sam I would like my website to show which users are logged in. Is there a simple way of retrieving all session ids from the server that have been allocated and are active in order to do this? I know this could lead to faulty information, but would appear to be the simplest and reliable. Thanks. Hello all...fairly new to this php/mysql thing... working on my final project thats due in about 24 hours... and i hit a rut... im making a pretty basic, online classifieds site. users can sign up, login, post new listings and view others listings by clicking on different categories. the problem i am having right now is this...When the user clicks on "My listings" i need it to pull only the listings that were created by that users user_id, which is the primary key in my user_info table...my professor suggested storing it in hidden field through the login submit button...very confused and frustrated... any help is much appreciated... Hai..
currently i am developing client dashboard using php/mysql.Here is my problem i need to create a tab named as notes.Using this tab the logged in users can add a new note or edit his existing note and save as text file.. I have dynamic images that have the "Like" button, it's basically like a wishlist. The way I want it to work is that when a user is not logged in, the 'Like' button will navigate them to a login popup (which I already made). Hi guys, I want a PHP Cookie & Session to apply to both the domain and all its subdomains, except one specific subdomain which I never want the same cookies/sessions to apply to. I have the apply too all sorted, just not the exception. Any help is much appreciated. I'm brushing up on Cookies and Sessions. My book says that in order to access the same Session data, you must have Code: [Select] session_start(); on each page that uses the Session data AND the user must have accepted the Session Cookie?! So what do you do if a user has Cookies Turned Off or Declines a Session Cookie?? (I find it hard to believe that Sessions are that "delicate"?!) TomTees Hello , my website uses sessions to check for users if they are logged in, get data and such stuff.. But i want to add cookies in order to make users stay logged in for more time.. I do have a remember me checkbox and a function that tells me if a user is loggedin by checking if session or cookie is set and then it returns a true flag... the problem is that i dont know how to get if he is logged via session or cookies Thanks. I'm trying to learn the proper workaround to enable Sessions when visitors have their cookies disabled.
When I create a PHP session page with ini_set("session.use_trans_sid", 1) and then disable my browser cookies and view browser source code, I see what I expect: a hidden input appended like this: It seems to work (sessions without cookies!). However, I don't see the long URL query strings that I used to see when I experimented with this 10 years ago, and I don't see the long PHPSESSID value appended to all the page links, and I don't see dozens of session variables appended as hidden form inputs. Rather, I just see the one PHPSESSID hidden input described above. Is this because all the session variables are stored on the server itself, and all the server needs is that one single long PHPSESSID value? Or, am I doing it wrong? :-) Edited April 4, 2019 by StevenOliver I have attached a very simple remember me script. Could someone please have a look at it and tell me if I'm doing it correctly, or what the correct implementation would be to allow users to not use and use the remember me function? I am having a hard time getting sessions and cookies to work as I would expect. I am using codelobster editor/debugger and wampserver. My problem is that when I try to delete a cookie it shows that the cookie is still there and active. <?PHP session_start(); date_default_timezone_set('Asia/Qatar'); // I try to delete the previous cookie which was set setcookie('my_session',"",time()-3600); // here I have a function that sets a cookie log_session("username","password"); session_destroy(); ?> When I check the local variables in the debugger they are still there and not deleted and have the same value. Is my logic wrong or is it my system? Hi, I want to end a session when a registered user is asked to login again but enters the incorrect credentials. I'm destroying the session and taking the user back to the login page, but for some reason when s/he clicks "back" on the browser s/he is able to get back into her/his account. Any ideas? I'm creating a login. When a user logs in, they can choose for the website to remember them. If they do, then the login function creates cookies. The function checks the database for the information and then stores it into an array and creates the cookies. HOWEVER when a user doesn't choose for the website to remember them, then I assume I will be using session variables. However, I am not sure how to go about it. Usually, I would create a cookie for the username and the password. Would it be safe to create session variables for the username and password to last for the session and then use these? I'm just confused how to deal with just a session.. I am using the scripts (at the end) on a shared debian server at my web host's remote facility. I'm very new to PHP and have been working on my site idea for the past couple of weeks and have been working on the basic sign up, logging in, activation and log out. The log out works fine, but when I sign in with a second username, the first user name's information comes up instead. Here's the log out script: <?php session_start(); session_unset(); session_destroy(); setrawcookie('user'); ?> I tried a bunch of other stuff but nothing seems to work. Closing the window and stuff works fine but obviously, that's not the safest method. I need advice on how to handle a php issue. I will try to simply my problem as best as I can. Index.php is used to upload multiple pictures engine.php is called each time for each picture. So if someone uploads 3 pictures engine.php is called 3 times and uploads each picture separately. What I want to be able to do is to track bulk uploads. For example, if someone uploads 10 pictures at once there would be a unique code in my database that I could query and see the results of the 10 pictures that where uploaded. Kinda like a batch. The problem is that I can't seem to create a unique code that it's used to to track batches. I have used cookies in my index.php and set it to a random variable. When my engine.php starts uploading images via POST method, it calls the cookie that was stores in index.php only to see that the value doesn't get passed. I check index.php by using echo $_COOKIE['...']; and a value does get into the cookie, but engine.php can't seem to access the cookie. (I used setcookie) Here's part of the code for the cookies (engine.php): $getmu = $_COOKIE['multiupload']; $insert_image = "INSERT INTO images (owner, dateadded, mimetype, originalfilename, filename, thumbname, filesize, description, originalip, originalwidth, originalheight, lastaccessed, tracker, mutracker) VALUES ($displayID, NOW(), '".preparedata($contenttype)."', '".preparedata($filename)."', '".preparedata($newfilename)."', '".preparedata($ranthumb)."' , '".preparedata($filesize)."', '".preparedata($imgdesc)."', '".preparedata($userip)."', '".$originalwidth."', '".$originalheight."', NOW(), '".preparedata($tracker)."', '".$getmu."')"; if I set $getmu to just any string, it seems to get inserted into the db, so it's not a syntax issue. When I use cookies, nothing gets inputed. I also tried using sessions, but since engine.php is called for each picture upload, the session changes for every picture. Any ideas or advice? I'm kinda stuck on this. The cookies should work, but they don't :/ Hello, On my site I offer the option an option for cookies or sessions on login. If a remember me box is selected, then a cookie will be set. My question is, how do I assign both the $_SESSION['id'] and $_COOKIE['id'] to the same variable? Thanks for the help! |