php session not being deleted after setting its lifetime - php

I am a php newbie and practicing with php sessions. Basically, I have a login form which will be shown to a user ONLY if the session does not exist otherwise the page says "User Already Logged In".
I have set the session life time and cookie time using :
session_set_cookie_params(60);
ini_set('session.gc_maxlifetime', 60);
I want the session to be destroyed after 1 minute so that the user will have to log in again. but in my implementation, the session still exists for a long time and the users are logged in.
in my login.php i have:
1: if visited login.php with POST req, then check login credentials
2:if SESSION['logged_in'] is set then do not show the form, echo "already logged in"
<?php
require_once("helpers.php");
session_start();
if(!empty($_POST)){
loginUser($_POST['user_id'], $_POST['pass']);
}
<?php
if(!isset($_SESSION['logged_in'])){
echo "<br>SESSION IS NOT SET UP";
?>
<HTML>
<HEAD>
<LINK rel="stylesheet" type="text/css" href="style.css">
<SCRIPT src="test.js"></SCRIPT>
</HEAD>
<BODY>
<H1>Please login</H1>
<FORM action="login.php" method="post">
<span class=formlabel>Username:</span>
<INPUT name="user_id" type="text" class="forminput" require><BR>
<span class=formlabel>Password:</span>
<INPUT name="pass" type="password" class="forminput" require><BR>
<INPUT type="submit" value="Login" style="width:80px;margin-left:100px;margin-top:3px;"><BR><BR>
Don't have an account? Click here to register.
</FORM>
</BODY>
</HTML>
<?php
}else{
echo '<strong>user already logged in.<br></strong>';
}
?>
Then in my helper.php I have a function:
1: check user id and password in data base
2: if it exists then set a session.
function loginCheck($user_id, $pass){
//here goes code which checks if user_id & pass exists
//store in $RESULT if exists
if(!empty($result)){
session_set_cookie_params(30, '/');
ini_set('session.gc_maxlifetime', 30);
$_SESSION['username'] = $user_id;
$_SESSION['logged_in'] = true;
}
}
Now when ever i log in as a user then the session starts and the login form dissapears, which is the correct behavior that i want. But the session never ends, i mean even if i refresh the page after 10 minutes the form doesn't show up and says "user already logged in".
also:
1: do the sessions gets destroyed by itself after their maxLifetime?
2: if not do we have to destroy it ?
thank you

The gc_maxlifetime value is the number of seconds after which data will be seen as garbage and potentially cleaned up. You'll want to make sure this value is set high enough so that your sessions aren't destroyed too early, but you can't rely on sessions being destroyed after this amount of time.
If you want sessions destroyed after a specific period of time, then you should store a timestamp, and then use that timestamp and the presence of the session to see if the session is still alive. Something like this:
$_SESSION['last_access'] = time();
Then later on, to check if it's still active:
if ( isset( $_SESSION['last_access'] ) && $_SESSION['last_access'] - 60 > time() ) {
// The session is still alive
} else {
// The session should be destroyed
session_destroy();
unset( $_SESSION );
}
Then, your future checks for the presence of any $_SESSION value will work the way you expect.

Related

Maintaining PHP Session Variables

I would like to maintain 3 $_Session variables after login. My login modal submits to my index.php page and this seems to be the only place I can access the session variables I set when the user logs in. How do I pass these variables to the next page the user visits? I know I can use hidden inputs in forms but what if the brows the site using the menu? I would like to store a users session variables in a session include file but I have the same issue passing the values of the variables from page to page.
-Mike
File a.php:
<?php
session_start();
$_SESSION['saveme'] = 'from file A';
?>
File b.php:
<?php
session_start();
echo $_SESSION['saveme']; // if you visited a.php previously, you will see "from file A"
?>
Setting a session variable in any file makes it available anywhere else.
You can store you values in session on one page(index in your case as you mentioned) then later on you can get those values on any page if session in started on that page. Session store those value till same session alive.
code to set values in session:
<?php
// Start the session
session_start();
?>
<?php
// Set session variables
$_SESSION["xyz"] = "xyz";
$_SESSION["abc"] = "abc";
echo "Session variables are set.";
?>
Code to get session values:
<?php
// Echo session variables that were set on previous page
echo "value of xyz is " . $_SESSION["xyz"] . ".<br>";
echo "value of abc is " . $_SESSION["abc"] . ".";
?>
The form of your modal
<form action="index.php" method="post">
Username <input type="text" name="username" />
Password <input type="password" name="password" />
</form>
Then you catch it in your index.php
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
// Check if user exists and password matches
$_SESSION['username'] = $_POST['username'];
$_SESSION['logintime'] = time();
$_SESSION['something'] = 'else';
}
In any other page you can use the values like
<?php
session_start();
if (isset($_SESSION['username'])) {
echo 'Welcome ' . $_SESSION['username'];
}
All who have provided answers thank you. This overlooked detail was all on me and though I have been out of the dev game for a while I should have known better.
My hosting service by default makes all file permissions read/write only...to access session variables I changed to read/write/execute and was successful.
Again thanks!

php session can't be found accrose pages [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a simple login page and
login.html - gets input username and pwd in form
login_result.php - connect to server and start session & form little form validation
note.php - this is the main page for user to choose other sub pages. so far I only display the user name on the screen to test the session works.
for viewing purpose, I've changed to html. please follow link to see what's wrong...
login_result
note
Your links seem to be of no help. Anyways I will give a little intro as to how to work with basic login and sessions.
login.html: The form which should be in the login.html page. Method MUST be POST as you are passing sensitive information to another page. Also note the names of the input fields.
<form role="form" method="POST" action="login_result.php">
<label for="UID">UserID:</label>
<input class="form-control" type="text" name="UID" required>
<br>
<label for="pwd">Password:</label>
<input class="form-control" type="password" name="pwd" required><br>
<button class="btn btn-default" type="submit">Login</button>
</form>
login_result.php: This is where the validation takes place.
<?php $username = trim($_POST['UID']); //UID is the name of the username input field
$pass = trim($_POST['pwd']); //So is pwd
if(strcmp($username,"admin") === 0 && strcmp($pass,"admin") === 0 )
{
session_start(); //start session
$_SESSION['username'] = $username;
//store userdata for further use.
//My page is simple so it just stores the username
header("Location: note.php"); //redirect to your "success" page
}
else
{
//Wrong credentials
header("Location: login.html");
}?>
The verification is basic here. I usually employ hashing but for now this will do fine
note.php: Reuse the Session variable to display the username like,
<h3>Welcome, <?php echo $_SESSION['username']; ?> </h3>
You must also check for each page if the session is active, and redirect to the login if its not, else there is no meaning to the login.
in_all_pages: Add this at the beginning,
<?php
session_start(); //start the session
if (!isset($_SESSION['username']) || empty($_SESSION['username']))
{
//redirect to the login
header("Location: login.html");
exit();
}
Remember to destroy the session like:
logout.php:
<?php
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
header("Location: login.html");
?>
To use PHP, the files must have .php extension.
Said that, to use the sessions you have to use this code line at the start of every php line:
session_start();

PHP cookies setting

I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.

Automatic Logout after 15 minutes of inactive in php

I want to destroy session if users are not doing any kind of activity on website.
At that time after 5 users automatically redirect on index page. How is it possible?
Is possible in php with session handling and for that I have to maintain or update user login time or not..
This is relatively easy to achive with this small snippet here:
if(time() - $_SESSION['timestamp'] > 900) { //subtract new timestamp from the old one
echo"<script>alert('15 Minutes over!');</script>";
unset($_SESSION['username'], $_SESSION['password'], $_SESSION['timestamp']);
$_SESSION['logged_in'] = false;
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
I got this solution from Sitepoint.com
Using a simple meta tag in your html
<meta http-equiv="refresh" content="900;url=logout.php" />
The 900 is the time in seconds that you want the session to be terminated if inactive.
Hope it works for you
Edit: This method does not implement any other logic so will only work if you want to "force" logout as said in the comments
You may create a cookie for a specific time.
For example you could put this on your login page:
<?php
setcookie('admin', 'abc', time()+50);
?>
Then in some file part that is included in every page, like 'header.php', you may include:
<?php
if (!isset($_COOKIE['admin'])) {
echo "<script> location.href='logout.php'; </script>";
}
setcookie('admin', 'abc', time()+50);
?>
In the above example, after 50s the cookie will die and the user will be logged out automatically.
Here is an example of the code.
session_start();
$t=time();
if (isset($_SESSION['logged']) && ($t - $_SESSION['logged'] > 900)) {
session_destroy();
session_unset();
header('location: index.php');
}else {
$_SESSION['logged'] = time();
}
My Solution Is
(i give you solution but this simple and syntax not been tried)
checkerOrCreatorTime.php
<?php
//if using the session, this additional advice me
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
session_start();
//create session (JUST FOR ONE TIME)
if (!isset($_SESSION['THE SESSION KEY FOR LOGIN (EX. USERNAME)'])){
//create anyting session you need
$_SESSION['user']['THE SESSION KEY FOR LOGIN (EX. USERNAME)'] = 'USER';
$_SESSION['user']['TIME'] = '900';
}else
if (time() -$_SESSION['TIME'] > 900){
unset($_SESSION['user']);
// and whatever your decision
}
?>
Faq:
1. Why use ['user'] is session login?
if you using many session for user, you just unset one var, like this.
2. why use a ini_set.... in this syntax?
for more security
if you like using modern web, just using javascript for ajax
<form action="index.php" method="post" name="frm"><input name="uname" type="text" placeholder="User Name" />
<input name="pass" type="password" placeholder="Password" />
<input name="submit" type="submit" value="submit" /></form>
In index.php
<?php if(isset($_SESSION['loggedAt'])) { header('dashboard.php'); }
if(isset($_POST['submit'])) { $name=$_POST['uname']; $pass=$_POST['pass'];
if($name=="admin" &amp;amp;&amp;amp; $pass=="1234") {
session_Start(); $_SESSION['username']=$name; $_SESSION['loggedAt']=time(); header('location:dashboard.php?msg=Welcome to dashboard'); } } ?>
in dashboard.php
if(time() - $_SESSION['loggedAt'] > 240) {
echo"<script>alert('Your are logged out');</script>";
unset($_SESSION['username'], $_SESSION['loggedAt']);
header("Location: " . index.php);
exit;
} else {
$_SESSION['loggedAt'] = time();
}
This code was included in the connection.php to ensure that the code is included in any page but you can implement on any page you want
if (isset($_SESSION['user-session']) OR isset($_SESSION['admin-session']) ) {
//then we are checking the activity sesssion $_SESSION['']
if (isset($_SESSION['last_active'])) {
//if the time is set then we check the difference
$max_time=5*60; #number of seconds
$now=microtime(date("H:i:s"));
//Checking the last active and now difference in seconds
$diff=round(microtime(date("H:i:s"))- $_SESSION['last_active']); #the difference of time
if ($diff>=$max_time) { #if the difference is greater than the allowed time!
//echo "logging out couse the time is".$diff;
header("location:logout.php");
}else {
$time=microtime(date("H:i:s"));
$_SESSION['last_active']=$time; #Updating the time
//echo 'More time added the time was!'.$diff;
}
}else{
//if there is no last active then we create it over here
$time=microtime(date("H:i:s"));
$_SESSION['last_active']=$time;
}}
Simple solution using .htaccess
Add the below lines to your .htaccess file where 3600 is the number of seconds.
Sessions will automatically be destroyed after certain time has nothing to do with the activity or inactivity.
According to the below code session will be destroyed after 1 hour.
php_value session.gc_maxlifetime 3600
php_value session.gc_probability 1
php_value session.gc_divisor 1

how to logout without logout.php

The php code below is login_successful.php which is obtained after user logs in, in this page i want to display his 'username' and a logout link
<html>
<head>
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:home.html");
}
?>
</head>
<body>
Welcome $myusername //here i want to display logged in user's name
Login Successful
</body>
</html>
how should i put logout link in this page without using another logout.php file.
Why use another page for logout? Do it like this
<?php
if(isset($_POST['logout'])) {
//Unset cookies and other things you want to
session_destroy();
header('Location: login.php'); //Dont forget to redirect
exit;
}
?>
<form method="POST">
<input type="submit" name="logout" />
</form>
You have to check wheter session has his username and then display, something like:
session_start();
if(isset($_SESSION['username'])){
echo "Hello, " . $_SESSION['username']);
echo "Logout"
}
You can always call session_destroy() to (guess what) destroy your sessions! From the manual:
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
More important than use session_destroy() is to make sure you reseted the cookie (if any used) by setting it's time one hour back: time() - 3600, like:
setcookie ("YourCookieName", "", time() - 3600);

Categories