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.
Related
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])
I have a problem in carrying session values between the pages.
I was struggling for 3 days for this issue.
Help me to overcome from this issue.
index.php (login page):
// initially declaring a variable with null value
!! include "conn.php";
#session_start();
if(isset($_SESSION['uname']))
{
$_SESSION['uname'] = " ";
}
else
{
$_SESSION['uname'] = " ";
}
?>
//later assigning the value
$usrname = $_POST['uname'];
$pass = $_POST['pass'];
$chk = mysqli_query($con,"select * from members WHERE username='$usrname'");
while($value = mysqli_fetch_array($chk))
{
$realpassword = $value['password'];
$_SESSION['uname'] = $_POST['uname'];
}
if(!isset($realpassword))
{
$realpassword = "";
}
if($realpassword == $pass)
{
echo "<script>window.location.assign('dashboard.php');</script>";
}
Dashboard.php (Dashboard):
// In dashboard
#session_start();
include "conn.php";
if(isset($_SESSION['uname'])&&$_SESSION['uname']!="")
{
$uname =$_SESSION['uname'];
}
else{
echo "<script>window.location.assign('http://www.website.com');</script>";
}
/// This page working fine
In page 3:
/// Session value not carried into this page .. when this page loads automatically logouts and redirect into home page
session_start();
include "conn.php";
if(!isset($_SESSION['uname'])&&$_SESSION['uname']=="")
{
echo "<script>window.location.assign('http://www.website.com');</script>";
}
$uname =$_SESSION['uname'];
You wrote :
if(!isset($_SESSION['uname']) && $_SESSION['uname'] == "")
{
echo "<script>window.location.assign('http://www.website.com');</script>";
}
Should be (OR not AND) :
if(!isset($_SESSION['uname']) OR $_SESSION['uname']==""){
echo "<script>window.location.assign('http://www.website.com');</script>";
}
Your code as pseudo code
index.php:
1 start a session
2 if uname is set in session, set it to one space
3 otherwise, set it to one space
4 get data from db
5 if we have data, set uname in session to POST data uname
in "page 3":
1 if uname is NOT set in session OR uname in session is empty string
2 logoff
3 otherwise
4 proceed ...
according to the other answer and 2) - 3) in index, Condition in 1) in "page 3" is never true. And in dashboard, you may see similar problems resulting from "deleting" the $_SESSION['uname'] with one space " " and checking for empty string ""
Change index.php:
include "conn.php";
#session_start();
unset($_SESSION['uname']); // delete previous values unconditionally (!)
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();
?>
When I use php header redirection all session variables are lost... Some people say that adding exit(); just after the header(""); will solve the problem but it doesn't seem to be the solution...
Can anyone please help?
Here is how I store variable into the session:
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['usr_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
if(empty($err)){
header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
Redirection code:
//connect database
require_once 'dbc.php';
page_protect();
$authorID = $_SESSION['user_id'];
if ( !empty($_POST["answ_content"]) && $authorID != 0 ) {
//vaqciot html chveulebriv texad
$content = htmlentities($_POST["answ_content"],ENT_COMPAT,'UTF-8');
$dro = date('Y-m-d H:i:s');
$qID = $_POST["question_ID"];
$author = $_SESSION["user_name"];
$sql="INSERT INTO wp_comments (comment_ID, comment_post_ID, comment_author, comment_author_IP, comment_date, comment_content, user_id)
VALUES
(NULL, '$qID', '$author', '123.123.123.123', '$dro', '$content', '$authorID')";
$result = mysql_query($sql);
//pasuxebis raodenobis ertit gazrda
$increase = "UPDATE wp_posts SET comment_count = comment_count+1 WHERE ID = $qID";
mysql_query($increase);
//gadamisamarteba shekitxvis gverdze
$url = 'Location:http://example.com/site/answ/question.php?ID=' .$qID;
header($url);
} else {
echo 'error';
}
You need to put exit(); after your header redirection, otherwise you have just loaded two pages of content into 1 page.
Also make sure you have session_start(); at the top of all your scripts.
You aren't starting the session. In order to use session variables and have them carry across pages, you need to put
session_start();
at the top of each page before anything else.
I was trying to set the session id of my own using :
session_id('own_generated_session_id_string');
But as the documentation says, you have to use this before
session_start();
Using it after session_start(), clears the session parameters.
Simples! make sure the page you are coming from (e.g. www.example.com) redirects to a (eg.g www.example.com/redirect.php) notice www at the beginning. If you change that from page to page, then yes things get wonky.
These sessions does not always work as we expect sometimes. I had a similar problem with my website using sessions that get lost. I basically solved it by injecting the value I want to keep on the session into the hidden text field the first time the page loads. Then the second time I call the page(page submit) I simply read the value from the hidden text field and carry on with rest of my code.
That's more easier and cleaner than using sessions in this case!
exit; should be placed after header redirection or session_regenerate_id(true); can be used
You just need to check the file permission in /var/lib/php directory
give yje public permisssion to /var/lib/php/session directory.
and all done.
Include session_start(); in both the files before the session.
Note don't use session_destroy() in the redirected file.
I am creating a login script that stores the value of a variable called $userid to $_SESSION["userid"] then redirects the user back to the main page (a side question is how to send them back where they were?).
However, when I get back to that page, I am echoing the session_id() and the value of $_SESSION["userid"] and only the session id shows up. It had occurred to me that maybe my redirect page needs to have at the top, but if this were true, then the session_id I'm echoing would change each time I end up on the page that is echoing it. Here is the script:
<?php
session_start();
include_once("db_include.php5");
doDB();
//check for required fields from the form
if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) {
header("Location: loginform.php5");
exit;
} else if($_POST["username"] && $_POST["password"]){
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit; }
} else if($_POST["email"] && $_POST["password"]) {
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit;}
} else {
//redirect back to login form
header("Location: loginform.php5");
exit;
}
mysqli_close($mysqli);
?>
You're doing this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
Where you should do this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $info["id"];
}
Make sure:
<?php
session_start();
Is at the top of each page.
Additionally, you can test by commenting out your redirects and echo'ing the value you're setting with to make sure you're retrieving/storing the correct value to begin with.
You need to call session_write_close() to store the session data changes.
Side answer: you can use the $SERVER["HTTP REFERER"] to redirect back, if it was filled by the browser