session active PHP, check in LOOP? - php

I have this function which I am using at the beginning of every of my PHP pages, which is working fine, if time has expired, the next CLICK on the page it will go out fine and go to usuarioLoginLogout.php.
function verificarSiEstoyConectado()
{
if( $_SESSION['last_activity'] < time()-$_SESSION['expire_time'] )
{
header('Location: usuarioLoginLogout.php');
}
else
{
$_SESSION['last_activity'] = time();
}
}
In my welcome page, I'm settings session variable as follows:
$_SESSION['logged_in'] = true;
$_SESSION['last_activity'] = time();
$_SESSION['expire_time'] = 60*3;
My doubt is if exists any way to check that function but in a LOOP, not to wait to the user to do click in any link of my site in order to check at the beginning of any page that if has expired or not?
If it possible, how could I implement this?
Thanks in advance,

Related

How to change PHP session time in this code?

I am trying to change the session time in my login code, and here is the code I want to change the session time in:
<?php
if(session_id()==='')
{
session_start();
}
if(!(isset($_SESSION['status']) && $_SESSION['status'] == "logged_in"))
{
die("sorry, you must be logged in to view this page");
} else {
?>
How would I go about changing the session time?
Also, if you can't change the session time in this, is there any code that can replace this and still work the same?
You may try session_cache_expire
session_cache_expire(30);
$cache_expire = session_cache_expire();
or see this

PHP session is dying on refresh why?

Hi each time im refreshing or click a button that reload my index page ... which is my main page, the session dies .... here is a simple of code :
//session.class.php
<?php
session_start();
$_SESSION["EMAIL"] = "";
$_SESSION["LOGED"] = 0;
?>
//index.php
<?php
include_once ('session.class.php');
if (isset($_GET['login'])) {/// it a button submit in my form that use for login
$_SESSION["LOGED"] = 1;
include ("/module/Users/profile.php");// class that show profile if login an
// password is good
echo "session = ".$_SESSION["LOGED"];
}
if ($_SESSION["LOGED"] == 0) {
echo userFormLogin();//show login
echo "<a href=index.php?content=register>Register</a>";
}
?>
TY every one :D
Every time you load page, your EMAIL and LOGED session variables get reset. You don't need to declare them, SESSIONS don't exist until you make one. You are basically creating session but when you load page it gets set to 0 and you ask for login again.
You should use:
if(isset($_SESSION['LOGED'])){
actions for logged in
}
else{
show login page
}

PHP Session believes it's being hijacked unless an echo is performed

I'm writing a simple website which allows a user to login, fill out a form which is submitted to a database and then log out. In order to manage the session, I used the session manager which is described by TreeHouse on the following page: http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions
In order to protect against hijacking, the client's IP address and user agent are stored in the session variable and compared to the server's values for these properties on each page. If they don't match, then it is assumed that the session has been hijacked and it is reset.
The implementation seems to work on my local machine without any issues, but when I uploaded it to the server, each page refresh causes the preventHijacking() function to return false (meaning it believes the session has been hijacked). However, if I echo any text within that function, the problem mysteriously disappears and the whole thing works as I expect it to (except for the bit of echoed text which is now displayed above my form :P).
I haven't a clue why this would be the case and I can't figure out how to fix it. The session manager code is below. At the start of each page, I use this to start the session and then each page simply uses or sets whatever variables it requires. If anyone could suggest why the function always returns false unless it echoes text and perhaps suggest what modification I need to make so that it will behave in the expected manner, I'd really appreciate it.
<?php
class SessionManager {
protected static $timeout = 600; // Time before automatic logout for the session
static function sessionStart($name, $limit=0, $path='/', $domain=null, $secure=null) {
// Set the cookie name before we start
session_name($name.'_Session');
// Set the domain to default to the current domain
$domain = isset($domain)? $domain : $_SERVER['SERVER_NAME'];
// Set the default secure value to whether the site is being accessed with SSL
$https = isset($secure)? $secure : isset($_SERVER['HTTPS']);
// Set the cookie settings and start the session
session_set_cookie_params($limit, $path, $domain, $secure, True);
session_start();
// Make sure the session hasn't expired and destroy it if it has
if(self::validateSession()) {
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking()) {
// Reset session data and regenerate ID
$_SESSION=array();
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session ID changing on any request
} else if (rand(1, 100) <= 5) {
self::regenerateSession();
}
$_SESSION['LAST_ACTIVITY'] = time();
} else {
$_SESSION = array();
session_destroy();
session_start();
}
}
static function preventHijacking() {
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent'])) {
return false;
}
if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) {
return false;
}
if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
return false;
}
return true;
}
static function regenerateSession() {
// If this session is obsolete, it means that there already is a new id
if(isset($_SESSION['OBSOLETE']) && $_SESSION['OBSOLETE'] === True) {
return;
}
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = True;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
static protected function validateSession() {
// Check if something went wrong
if(isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
return false;
}
// Test if this is an old session which has expired
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
return false;
}
// Check if the user's login has timed out
if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > self::$timeout) {
return false;
}
return true;
}
}
?>
I could be way out here (it's been a while) but that sounds like the buffer containing the headers isn't being flushed for some reason. Providing body would force them to be flushed, so maybe not providing the body doesn't flush?
Try putting ob_end_flush(); in there before you return. That may fix it.

logging out a user completely from a website [duplicate]

This question already has answers here:
PHP ending sessions(different ways) i dont understand
(2 answers)
Closed 9 years ago.
I have a PHP login and log out script and what I'm trying to achieve is that when the user click on the log out link he completely logs out, regardless clicking the back button of the browser, and do not want the user to access the page.they should be redirected to the login page
this is login function
function loggedin() {
if ( isset($_SESSION['user_id']) && !empty($_SESSION['user_id']) ) {
return true;
} else{
return false;
}
}
and this is my logout script
<?php
include 'includes/connect.php';
include 'includes/functions.php';
session_destroy();
header('location: index.php');
?>
how can i achieve this??
You can delete all cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
http://www.php.net/manual/en/function.setcookie.php#73484
And if you have an array of cookie names used for login authentication, you should iterate the cycle only with them.
The question was logging out a user completely from a website and not just how do I destroy a PHP session, so my answer will be somewhat more complex.
Since you're using PHP's $_SESSION functionality to handle the user sessions, you can, in particular, tie the current session IDs to the user accounts. Then you can easily force the session to expire.
For example, create a new field in the user database, and call it active_session_id or something. Every time a user logs in, save the session_id() output to it. Then inside of your loggedin() function check if the session_id() of the current request matches the one saved when the user was logging in, and if it does not match, the function will return false, so this is how you virtually end a user session. I.e. even though it will still actually be there, it will not be valid anymore.
It is worth noting that the solution above would be sort of a one-to-one relation, i.e. one user will be able to have only one active session. If you want to allow users to come from different places at the same time, you'll have to maintain a one-to-many relation there by creating a new table called e.g. users_sessions and saving the session IDs there. Please do not create another fields in the current users table like active_session_id_1, active_session_id_2 etc. because it is not considered to be a good practice.
Hope this helps
You can write a generic function that checks if a user is logged in, if not just redirect them like this
function isLoggedIn(){
if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
//do what you want
} else{
header("location:youloginpage.php");
}
}
If you do not specify more on your question, we can only procede by assumptions. Anyway, since you are using that SESSION, and it's not clear if you want to destroy the data contained or not, the function to check if user is logged in, could be modified this way:
function loggedin() {
if ( isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']) && ($_SESSION['user_id'] > 0) ) {
return true; //user is logged in
//other operations to be performed
} else{
return false; //user is NOT logged in
//other operations to be performed
}
}
The logout function could just be something like this:
function logout() {
if ( isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']) && ($_SESSION['user_id'] > 0) ) {
$_SESSION['user_id'] = -1; //"unsets" the user, while not destroyng session
} else{
return false; //user is already logged out - do nothing
}
}

creating an automatic logout page in php

i am trying to write a automatic logout script which seems to work but not to my expectations,i do not know what exactly im doing wrong,i want to put the timeout.php on every page so that when the user is idle it logs out automatically and redirects it to login page but when i put the timeout.php on for my add user page where admin adds users,its overriding the link for the add user page and putting a login page which is also not coming out nicely(i.e the form is getting out of its position)
this is the timeout.php code
<?php
$_SESSION = 0;
if($_SESSION['session_count'] == 0) {
$_SESSION['session_count'] = 1;
$_SESSION['session_start_time']=time();
} else {
$_SESSION['session_count'] = $_SESSION['session_count'] + 1;
}
$session_timeout = 10; // (in sec)
$session_duration = time() - $_SESSION['session_start_time'];
if ($session_duration > $session_timeout) {
session_unset();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION["expired"] = "yes";
header("Location: login.php"); // Redirect to Login Page
} else {
$_SESSION['session_start_time']=time();
}
?>
i want it to automatically logout and redirect itself to the login page with a message yoour session has expired and i want it to put it on every page without it disturbing the forms or overlapping the page

Categories