header('location:index.php') doesn't work in the first run - php

I have an index.php page that a session is set inside($_SESSION['expire']). This session should be unset after 30 mins and we should redirect to index.php (to verify the user again).
some part of my index.php code:
<?php
session_start();
//if user name and password are valid do the following:
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60) ;
?>
<a href="index.php?action=ContentManager">
content
</a>
<?php
if(isset($_REQUEST['action']))
{
//if the expiration time has not reached yet do the following
$now=time();
if (isset($_SESSION['expire']) && ($now<= $_SESSION['expire']))
{
switch($_REQUEST['action'])
{
case 'ContentManager' :
include('model/content.php');
$contents = getContent($conn, ' where 1=1');
include('view/contentmanager.php');
break;
}
}
else if($now > $_SESSION['expire'])
{
unset($_SESSION['expire']);
session_destroy();
header('location:index.php');
exit();
}
}
?>
the problem is that when I click contentmanager link after 30 mins, we will redirect to an empty page with url:
index.php?action=contentmanager
And only if I refresh the page again, we will redirect to index.php itself and the login form will be appeared.
So breifly: I have to refresh the page two times to redirect to the correct page.
Thanks in advance

use ob_start();
<?php
session_start();
ob_start();
//if user name and password are valid do the following:
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60) ;
?>
<a href="index.php?action=ContentManager">
content
</a>
<?php
if(isset($_REQUEST['action']))
{
//if the expiration time has not reached yet do the following
$now=time();
if (isset($_SESSION['expire']) && ($now<= $_SESSION['expire']))
{
switch($_REQUEST['action'])
{
case 'ContentManager' :
include('model/content.php');
$contents = getContent($conn, ' where 1=1');
include('view/contentmanager.php');
break;
}
}
else if($now > $_SESSION['expire'])
{
unset($_SESSION['expire']);
session_destroy();
header('location:index.php');
exit();
}
}
ob_end_flush();
?>

Related

Session timeout stuck in loop

I'm stuck in a session timeout loop,
Once my session times out i can't sign back in
<?php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 300)) {
header("location:../index.php");
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
here is where I included the timeout.php
<?php
//$now = 0;
if (isset($_REQUEST['err'])){
$now = $_REQUEST['err'];
}
?>
<?php
session_start();
include('../includes/session_timeout.php');
if(!isset($_SESSION['isactive'])){
header('location: index.php?e=li');
}
include('../../administrator/includes/constants.php');
include('../includes/functions.php');
if(isset($_REQUEST['p'])){
$cmd = $_REQUEST['p'];
}else{..........etc
Try to unset your session variable before redirecting
session_start();
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 300)) {
unset($_SESSION['LAST_ACTIVITY']);
header("location:../index.php");
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Session time out when idle not working php

I have written some code to timeout a session;
<?php
session_start();
// set timeout period in seconds
$inactive = 10;
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$SESSION_life = time() - $_SESSION['timeout'];
if($SESSION_life > $inactive)
{ session_destroy(); header("Location: login.php");exit; }
}
$_SESSION['timeout'] = time();
if (isset($_SESSION['username'])) {
echo "<center>Welcome </center>" ; // echo "<p> </p>";
echo " <center>". $_SESSION['username']. "</center>" ;
echo "<br /><center>".$_SESSION["role"]."<br /></center>" ;
}else{
header("location:login.php");
}
However, the session does not timeout if it's idle for 10 seconds.
Looks like your almost there. I would try this:
<?php
session_start();
$inactive_time = 10;
if(isset($_SESSION['last_active_time'])){
$time_since_last_active = time() - $_SESSION['last_active_time'];
if($time_since_last_active >= $inactive_time){
// The user has been inactive for too long
session_destroy();
header('Location: login.php');
exit;
}else{
// Set the last active tim
$_SESSION['last_active_time'] = time();
}
}else{
$_SESSION['last_active_time'] = time();
}

Issues with my timeout script

I'm running a script that will destroy a user's session after a certain amount of inactive time. However, it's not running correctly. Can someone explain to me what I'm doing wrong?
<?php
require("../includes/header.php");
$expire = time();
echo $expire ."<br>";
if(!isset($_SESSION["expire"]) < ($expire + 30)){
setcookie("User", $_SESSION["user"], 30);
echo "Welcome " .$_SESSION["user"];
$_SESSION["expire"] = $expire;
}
elseif($_SESSION["expire"] > ($expire + 30)){
unset($_COOKIE["User"]);
session_unset();
session_destroy();
header("Location: logged_out.php");
}
?>
$expire will always equal $_SESSION["expire"] because you set $_SESSION["expire"] equal to $expire at the top of the page and never change their values.
Set $_SESSION["expire"] after you validate the user. Also, your logic seems to be incorrect:
<?php
require("../includes/header.php");
$now = time();
$expires = $_SESSION["expire"] + 30;
if(!isset($_SESSION["expire"]) || $expires > $now){
setcookie("User", $_SESSION["user"], 30);
echo "Welcome " .$_SESSION["user"];
$_SESSION["expire"] = $now;
}
else {
unset($_COOKIE["User"]);
session_unset();
session_destroy();
header("Location: logged_out.php");
}
?>

refresh problem in online users list

I have a problem with the online users list.
The code works fine, all the online users are displayed on the screen but when I click on refresh, the same user's email is displayed again and when I click on refresh for the second time the user's email is displayed three times and so on.
Here is my code:
<?php
require_once("db.php");
db_connect();
session_start();
$player_timeout = time() - 5 * 60;
$time = time();
if (isset($_SESSION['email'])) {
$login=mysql_query("insert into activePlayer(player_email,time_visited,status) values('".$_SESSION['email']."','".$time."', 'true')");
}
else
{echo "You are not logged in";}
$tmout = mysql_query("DELETE FROM activePlayer WHERE time_visited < ".$player_timeout);
$online_member = mysql_query("SELECT player_email FROM activePlayer");
$row=mysql_num_rows($online_member);
$member_row=mysql_fetch_array($online_member);
echo "Welcome '".$_SESSION['email']."'";
?>
<body>
<select > <?php
if ($row<1)
{
echo " ";
}
else
{?> <p><p>Online Players:<option><?php echo $member_row['player_email'];?>
</option>}
<?php for ($i=1;$i<$row;$i++)
{
$member_row=mysql_fetch_array($online_member);?>
<p><p>Online Players:<option><?php echo $member_row['player_email']; }}?>
</option></select>
</body>
please how can I solve this problem
Every time you refresh you insert a row into the db if the user is logged in. You have to check if the user already exists in the db and update his record instead. If he has no record then just create a new as you do.
$hasRow = mysql_query("SELECT * FROM activePlayer WHERE player_email='".$_SESSION['email']."' LIMIT 1");
if(mysql_num_rows($hasRow) > 0) {
$login = mysql_query("UPDATE activePlayer SET visited=".time()." WHERE player_email='".$_SESSION['email']."'");
} else {
$login=mysql_query("insert into activePlayer(player_email,time_visited,status) values('".$_SESSION['email']."','".$time."', 'true')");
}
What you need to do is a redirect:
if (isset($_SESSION['email'])) {
mysql_query("INSERT INTO activePlayer (player_email,time_visited,status)
VALUES ('".$_SESSION['email']."','".$time."', 'true')");
unset($_SESSION['email']);
header("Location: otherpage.php"); // or it can be the same page
}

PHP - make session expire after X minutes

i am using the following technique...
From the login.php the form posts to the page check.php where i do this
<?php
$uzer = $_POST['user_name'];
$pass = $_POST['user_pass'];
require ('DB_connection.php');
$result = mysql_query("SELECT * FROM accounts WHERE user_Name='$uzer' AND user_Pass='$pass'");
if( mysql_num_rows( $result ) > 0)
{
$array = mysql_fetch_assoc($result);
session_start();
$_SESSION['user_id'] = $uzer;
header("Location:loggedin.php");
}
else
{
header("Location:login.php");
}
?>
and on loggedin.php page the first thing i do is
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) )
{
header("Location:login.php");
}
else
{
echo ( "this session is ". $_SESSION['user_id'] );
//show rest of the page and all
}
?>
but once logged in when i directly type the url localhost\myProject\loggedin.php it displays the page...which makes perfect sense because the session has started
what i want to implement is
The direct URL \ session works for 10 minutes after that the session is terminated\expired\timed out and then use must login again and may get the same session id but after 10 minutes use won't be able to browse with the same session
WHAT DO I NEED TO DO OR LEARN
Store a timestamp in the session:
<?php
$uzer = $_POST['user_name'];
$pass = $_POST['user_pass'];
require ('DB_connection.php');
// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($uzer), mysql_real_escape_string($pass));
if( mysql_num_rows( $result ) > 0)
{
$array = mysql_fetch_assoc($result);
session_start();
$_SESSION['user_id'] = $uzer;
$_SESSION['login_time'] = time();
header("Location:loggedin.php");
}
else
{
header("Location:login.php");
}
?>
Check if the timestamp is within the allowed time window (600 seconds is 10 minutes):
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 600)
{
header("Location:login.php");
}
else
{
// uncomment the next line to refresh the session, so it will expire after ten minutes of inactivity, and not 10 minutes after login
//$_SESSION['login_time'] = time();
echo ( "this session is ". $_SESSION['user_id'] );
//show rest of the page and all
}
?>
I would look at session_set_cookie_params and ini_set("session.gc_maxlifetime", "18000");
Use session set cookie function in your php file where you will start session, it will expire after as per define x minutes.
session_set_cookie_params(600);
As per above after 10 minutes session is expire.

Categories