PHP simple session-timeout - php

I have a project for university in which we should develop a static website with free session.
I need a simple php timeout code.
Is correct to use this? code:
<?php
if ($_SESSION['timeout'] + $minutes * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
$_SESSION['timeout'] was set to time();

it depends on your website logic. Try to use this if you want.
<?php
session_start(); $t=time(); $diff=0; $new=false;
if (isset($_SESSION['time'])){
$t0=$_SESSION['time']; $diff=($t-$t0); // inactivity period
} else {
$new=true;
}
if ($new || ($diff > 10)) { // new or with inactivity period too long
//session_unset(); // Deprecated
$_SESSION=array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) { // PHP using cookies to handle session
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 3600*24, $params["path"],
$params["domain"], $params["secure"], $params["httponly"]);
}
session_destroy(); // destroy session
// redirect client to login page
header('HTTP/1.1 307 temporary redirect');
header('Location: login.php?msg=SessionTimeOut');
exit; // IMPORTANT to avoid further output from the script
} else {
$_SESSION['time']=time(); /* update time */
echo '<html><body>Tempo ultimo accesso aggiornato: ' .$_SESSION['time'].'</body></html>';
}
?>
But I suggest to use session_regenerate_id() instead of session_destroy()

Related

Destroy the Session File after logout

I have this code for Login where I am storing following in the session variables:
if($do == "login") {
session_start();
$_SESSION["valid"] = true;
$_SESSION["studentUniqueId"] = $user_row['studentUniqueId'];
$_SESSION["loginName"] = $loginName;
$_SESSION["timeout"] = $now;
}
Session file looks likethis:
valid|b:1;studentUniqueId|s:5:"10001";loginName|s:13:"abc#gmail.com";timeout|s:19:"2015-07-01 18:26:32";
Also the code for logout where I am destroying the user session:
if($do == "logout") {
session_start();
$_SESSION = array();
session_unset();
session_destroy();
}
After logout the session files contains:
valid|b:0;
Even I have used session_destroy(), after logout the session file exist with valid|b:0; on my servers Temp directory and the size of the temp directory increases considerably.
I want to get rid of these files after session_destroy()/logout which is not the way now.
Is any way I am going wrong with the code.
Edit 2 :(erasing complete session data, you can use the below code)
ini_set('session.gc_max_lifetime', 0);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
Edit 1 (original) : Try this from PHP MANUAL
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Use this too
ini_set('session.gc_max_lifetime', 0);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
// Finally, destroy the session.
session_destroy();
?>

PHP Destroy session on isset

I am trying to destroy a session when a session is selected but it is not being destroyed:
if (isset($_POST['primary_cat'])) {
$_SESSION['primary_cat'] = $_POST['primary_cat'];
unset($_SESSION['secondary_cat']);
}elseif(empty($_SESSION['primary_cat'])) {//define primary_cat
$_SESSION['primary_cat'] = null;
}
When I change $_POST['primary_cat'] this is changed but $_SESSION['secondary_cat'] is not being destroyed. How can I destroy $_SESSION['secondary_cat']
This is how I completely destroy the one and only session I have:
session_start();
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params["path"],$params["domain"], $params["secure"], $params["httponly"]);
echo " Zerstöre Cookie... ";
}
#session_unset();
#session_destroy();
Maybe it helps you to adapt your code for your specific session.
if (isset($_POST['primary_cat'])) {
$_SESSION['primary_cat'] = $_POST['primary_cat'];
unset($_SESSION['secondary_cat']);
} elseif (empty($_SESSION['primary_cat'])) {//define primary_cat
$_SESSION['primary_cat'] = null;
}
You should try these instead:
if (isset($_POST['primary_cat'])) {
session_destroy();
$_SESSION['primary_cat'] = $_POST['primary_cat'];
} else if (!$_SESSION['primary_cat']) {
//your business
}
An explanation to that is on clicking or selecting
"primary_cat"
it should run that block of code else it won't run that code and if it does, you the
session_destroy();
Destroys active session and the below creates a new session due your specifications.
Your code seems ok, problem might be from your browser.
make sure session is started. if it's still not destroyed, then close your browser and restart apache.
But also make sure you are not setting $_SESSION['secondary_cat'] somewhere else your code.
To be sure, do the following after unsetting $_SESSION['secondary_cat']
if(isset($_SESSION['secondary_cat'])){
echo '<script type="text/javascript">alert("the session still has value : '.$_SESSION['secondary_cat'].'");</script>';
}
else
echo '<script type="text/javascript">alert("session has been unset");</script>';
The above will display a javascript alert showing "the session still has value : thevalue" if the session was not unset or "session has been unset" if it really has been unset
hope this helps
try this...
if(isset($_SESSION['secondary_cat'])&&!empty($_SESSION['secondary_cat'])){
unset($_SESSION['secondary_cat']);
}

Cookies are not removing on Log Out

I've got a problem, user can't Log Out because the $_COOKIE's are not actually deleting. I can't find out what could be the problem.
This code is used only once at Log In:
// Log In
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('user_id', $row['user_id'], time() + 2592000);
setcookie('username', $row['username'], time() + 2592000);
The code below is checking if cookies are set up to make users to be logged in when they relaunch their browser (the "keep me logged in" effect).
// Starting Session
session_start();
// If the session vars aren't set, try to set them with cookies
if (!isset($_SESSION['user_id'])) {
// This check always equals true because cookies are not deleting on Log Out
if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['username'] = $_COOKIE['username'];
}
}
This code is launched only once on Log Out:
// Log Out
session_start();
if (isset($_SESSION['user_id'])) {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 2592000, '/');
}
session_destroy();
}
setcookie('user_id', '', time() - 2592000);
setcookie('username', '', time() - 2592000);
Don't use relative times for cookies. if you want to expire a cookie, then use Jan 1 1970 00:00:00. You're assuming that the user's clock is accurate and within an hour of your server's. Given how many people have their VCRs blinking 12:00, this is a bad assumptiong.
As well, why are you storing login information in a client-side cookie? The only cookie you should really be setting is the session cookie, which session_start() already does for you, then store all that information in $_SESSION only.
I think you're doing it way too complicated.
My example where it's just an admin login:
login.php
#session_start();
if (isset($_GET['login'])) {
if($_GET['name'] == $s['admin']){
if($_GET['pw'] == $s['adminpw']){
$_SESSION['isadmin'] = true;
}
}
}
logout.php
#session_start();
unset ($_SESSION['isadmin']);
use session_set_cookie_params() to set the lifetimes
I found why cookies were not removing!
To make sure your cookies will remove, set the same path on removing cookies as on setting them.
// Setting Cookie
setcookie(session_name(), '', time()-2592000, '/'); // The path here is "/"
// Removing Cookie
setcookie(session_name(), '', time()+2592000, '/'); // The path here is "/"

Php sessions being lost

I do the following to set my session, this works because the echo appears. but when I go to the next page or another the session is not there? what am I doing wrong?
$session_start();
if ($username==$dbusername&&$password==$dbpassword)
{
echo"<b>Login Successful</b><br><a href='systemadmin.html'><br>Click here to access the <strong>System Admin Page</strong></a>";
$_session['username']=$dbusername;
if($username == "admin")
{
$_session['admin'] = true;
}
I am trying to get the following to work with these sessions:
<?php
session_start();
if($_session['admin'] == true)
{
// do nothing
}else{
header( 'Location: home.html' ) ;
}
?>
Update:
the uppercase sessions work but now the sessions arent destroying when i use the logout.php
<?php
session_start();
session_destroy();
header("location: home.html");
?>
$_session should be => $_SESSION.
http://php.net/manual/en/reserved.variables.session.php
The first works because you are setting a 'normal' variable (which is available for the request).
UPDATE
To destroy the session:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
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();
?>
http://php.net/manual/en/function.session-destroy.php#example-4368
Additionaly you should always use exit(); after you do a redirect to prevent further execution of the script.
PHP Server/Session/Global variables are case sensitive. To PHP, $_SESSION is NOT the same variable as $_session, even though to you in English, they seem to be. You must use $_SESSION, not $_session in order to access the PHP Session variables as you are expecting.
You have to use exit(); after the header(); because the script doesn't always end right after the user redirects to a new page.
The name of the superglobal is $_SESSION in uppercase letters. Try changing that and see if it helps.

a log-out hyperlink in PHP?

In case somebody knows, how can I make a hyperlink in PHP...
<?php
echo( 'Log-out' );
?>
that would not only to navigate to the first page, but also remove cookies?
Thanks!
You can make another page which clears all the cookies (i.e. sets them to expire in the past) and then redirects to index.php:
// page: clear.php
<?php
session_start();
$_SESSION = array();
session_destroy();
setcookie('cookie1', '', strtotime('-2 days'));
setcookie('cookie2', '', strtotime('-2 days'));
// etc.
header('Location: index.php');
exit();
I usually use the method prescribed by the manual:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
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();
?>
The only thing that remains is header('Location: index.php');
Submit a parameter in your link like index.php?logout=true, check for that parameter in your index.php and if set, delete cookies:
http://php.net/manual/de/function.setcookie.php
If you set the "lifetime" (expire) of a cookie to something in the past (or leave it out completely), it will be removed on the next pageload (do a Google search for "php delete cookie" to find help). Force a page reload, if needed.
You may also want to destroy the user's session.
Here's your HTML link
Log-out
And your PHP to handle to logging out
if(isset($_GET['logout'])) {
// clear the session variable, display logged out message
}
Use link like that:
<?php
echo( 'Log-out' );
?>
And index.php is:
<?php
$link = $_GET["link"];
if($link == "logout")
{
session_destroy();
}
?>
In the navigation menu:
Log out
In logout.php:
<?php
// kill the session
header('Location: index.php');
exit();
For killing the session, see the example at session_destroy() in the PHP manual.
Logout Link:
Log Out
logout.php
<?php
session_start();
session_destroy();
?>

Categories