How to expire a php session after certain time? [duplicate] - php

This question already has answers here:
How do I expire a PHP session after 30 minutes?
(17 answers)
Closed 5 years ago.
I have the following code:
The page Login.php
<?PHP
session_start();
include("conexion.php");
$conn = conexion();
extract($_POST);
$password = md5($pass);
echo $password;
$sql1="Select * from miembro where user='".$user."'and pass ='".$password."'";
$re= mysqli_query($conn,$sql1);
$numrows1 = mysqli_num_rows($re);
echo $sql1;
echo $numrows1;
if ($numrows1==0 or $numrows1>=2){
$_SESSION['session'] = "no";
header('Location:' . getenv('HTTP_REFERER'));
}else{
$row = mysqli_fetch_array($re);
$_SESSION['nombre'] = $row["nombre"];
echo $_SESSION['nombre'];
$_SESSION['codigo'] = $row["codigo"];
$_SESSION['pass'] = $row["pass"];
$_SESSION['apellido'] = $row["apellido"];
$_SESSION['telefono'] = $row["telefono"];
$_SESSION['user'] = $row["user"];
$_SESSION['cargo'] = $row["cargo"];
$_SESSION['correo'] = $row["correo"];
$_SESSION['session'] = "si";
$_SESSION['last_time'] = time();
header("Location: ./actions/perfil.php");
}
?>
And perfil.php (where the user is taken once logged in)
<?php
include("./menu_actions.php");
include("../conexion.php");
if($_SESSION['session'] != "si"){
header("location: ../home.php");
}
$us = $_SESSION['user'];
$sql="select * from miembro where user = '$us';";
echo $sql;
$query = mysqli_query(conexion(),$sql);
$row = mysqli_fetch_array($query);
session_start();
if(isset($_SESSION["user"])){
if((time() - $_SESSION['last_time']) > 10){ //After 10 sec
header("location:logout.php");
}
}
else{
header('Location:login.php');
}
?>
//HTML
It's not working and I don't understand why. The time of the start of the session is kept in a variable and analyzed later with an if loop, so if the time exceeds 10 seconds, the user should be forced out and taken to the login page again, but I can't make it work. Could somebody help me, please?

Hmm, maybe try to set cookie in this way:
setcookie($cookie_name, $cookie_value, time() + 10, "/"); // 86400 is one day
then check is it set instead by isset($_COOKIE[$cookie_name])

Related

What's wrong with my login system? [duplicate]

This question already has answers here:
Incorrect Integer (2147483647) is inserted into MySQL?
(11 answers)
Closed 4 years ago.
I'm trying to make a login system in PHP but it isn't working as intended. The code is supposed to generate a random integer and assaign it to a cookie named "token", then it uploads the value of the cookie to a database. If there is no token, it redirects the user to a 404 page, or if the token isn't equal to the token in the database it also redirects the user to a 404 page. But when I login, instead of setting the token in the database to the cookie's value, it sets it to 2147483647. How can I make the PHP code set the token in the database to the cookie's value?
Code:
admin.php:
include_once "connect.php";
if (!empty($_POST['user']) && !empty($_POST['pass'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$_user = mysqli_escape_string($conn, $user);
$_pass = mysqli_escape_string($conn, $pass);
$query = "SELECT * FROM supa WHERE user='$_user' AND pass='$_pass'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_assoc($result) > 0) {
setcookie("token", random_int(111, 8942));
$ok = $_COOKIE['token'];
$conn->query("INSERT INTO token (token) VALUES ('$ok')");
echo "<script>location.href = \"panel.php\"</script>";
} else {
echo "Wrong Cridentials";
}
}
panel.php:
include_once 'connect.php';
if (!empty($_COOKIE['token'])) {
$token = $_COOKIE['token'];
$query = "SELECT * FROM token WHERE token='$token'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_assoc($result) > 0) {
} else {
echo "<script>location.href = \"/\";</script>";
}
} else {
echo "<script>location.href = \"/\";</script>";
}
It seems that you have a type problem in your database. 2147483647 is the highest number of a 32 bits integer.
I guess you have to change your type in your database from int to varchar or something.
Try this:
$token = random_int(111, 8942) ;
setcookie("token", $token);
$conn->query("INSERT INTO token (token) VALUES ($token)");
$url = 'panel.php' ; // preferrably: absolute path.
header("Location: $url");
exit;
Next: see the very important tips in the remarks under your question.

Need MySQL db for php script

I want to make a shop for my website, so I need MySQL.
I want to take 50 Golds from the user, and give 5 atkdmg.
My current script looks like this:
<?php
ob_start();
session_start();
print('<meta http-equiv="content-type" content="text/html; charset=UTF-8"
/>');
include('config.php');
if(isset($_SESSION['rank']) && $_SESSION['rank'] >= 1)
{
if(isset($_SESSION['Gold']) && $_SESSION['Gold'] >= 50)
{
mysql_query("UPDATE users SET Gold = $_SESSION[Gold]-50 WHERE id =
$_SESSION[id];");
mysql_query("UPDATE users SET AtkDmg = $_SESSION[AtkDmg] + 5' WHERE id =
$_SESSION[id];");
} else header('location: shop.php');
} else header('location: login.php');
mysql_close()
?>
What is session? here it is:
<?php
ob_start();
session_start();
include('config.php');
include('login_form.php');
if(isset($_POST["login"])){
$nickname = $_POST["nickname"];
$password = md5($_POST["password"]);
$lekerdezes = mysql_query("SELECT * FROM users WHERE nickname =
'".mysql_real_escape_string($nickname)."' AND password = '$password'");
$vanelekerdezes = mysql_num_rows($lekerdezes);
if ($vanelekerdezes>0)
{
header('location: login.php');
$adatok=mysql_fetch_assoc($lekerdezes);
$_SESSION["id"]=$adatok["id"];
$_SESSION['bann'] = 0;
$_SESSION["nickname"]=$adatok["nickname"];
$_SESSION["rank"]=$adatok["rank"];
$_SESSION["Gold"]=$adatok["Gold"];
$_SESSION["AtkDmg"]=$adatok["AtkDmg"];
}
else
{
print 'Hibás felhasználónév vagy jelszó!';
print mysql_error();
}
} else if(isset($_SESSION["nickname"])){
header('location: home.php');
}
?>
I hope you can help me, I'm still learning PHP, so maybe that's why I can't fix this simple thing... So if you would write: learn PHP, I'm already doing that :)
First, adjust the session var:
$gold = $_SESSION['Gold'] = $_SESSION['Gold'] - 50;
$attackDamage = $_SESSION['AtkDmg'] = $_SESSION['AtkDmg'] + 5;
Edit your SQL strings like this:
"UPDATE users SET AtkDmg = $attackDamage etc etc

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();
}

PHP Session expiration - works stand alone but not in a function

when I issue this code from a function, the cookies expire at the end of the session
$validuntil = '2024-02-17';
$validuntil = strtotime ($validuntil);
setcookie ('vid',$vid,$validuntil,'/');
setcookie ('pwd',$pwd,$validuntil,'/');
However, executing the exact same code in a stand alone php file sets the cookies to expire on the correct date.
Here is the function
function validuser ($vid, $pwd){
global $pdo;
$stmnt = $pdo->prepare ("select * from members where vid = :vid and password = :password");
$stmnt->bindParam (':vid',$vid);
$stmnt->bindParam (':password', $pwd);
$stmnt->execute();
if ( $stmnt->rowCount() != 1){
header("Location:invalid.php");
break;
}
$member = $stmnt->fetch (PDO::FETCH_OBJ);
if ($member->nickname!="")
$_SESSION['user']= $member->nickname." ".$member->lname;
else
$_SESSION['user']= $member->fname." ".$member->lname;
$validuntil = '2024-02-17';
$validuntil = strtotime ($validuntil);
setcookie ('vid',$vid,$validuntil,'/');
setcookie ('pwd',$pwd,$validuntil,'/');
$_SESSION['ulot'] = $member->ulot;
$_SESSION['valid'] = '101150';
$_SESSION['admin'] = $member->admin == 1;
$_SESSION['vid'] = $member->vid;
$_SESSION['resid'] = $member->vid;
$_SESSION['pwd'] = $member->pwd;
$_SESSION['user'] = $member->fname." ".$member->lname;
header ("Location:mainmenu.php");
}
Can someone please explain this and how I fix it.
Thanks,

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