stop session from logging user out - php

I have some code that I added to try and prevent the user from auto logging out (session). - but it still logs the user after so long
What I want is for the user to be able to access multiple pages when logged in and not log them out if they go idle, hence why I put a large idle time - or in other words , stay logged in until they decide to click logout.
login-page
$result = mysqli_query($connection,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION['username']=time();
// Redirect user to index.php
header("Location: admin-index.php");
}else{
$_SESSION['incorrect'] = 'Incorrect email or password. Please try again.';
header ("Location: admin-login.php?=incorrectlogin");
}
}
logged in index page
<?php
session_start();
$idletime=6000000;
if (time()-$_SESSION['username']>$idletime){
session_destroy();
session_unset();
header ("Location: admin-login.php");
}else{
$_SESSION['username']=time();
}
//on session creation
$_SESSION['username']=time();
?>
<!DOCTYPE html>
<html lang="en" >
<head>
second php page
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: admin-login.php");
exit(); }
?>

There are a few ways of handling this:
You could change the lifespan of the sessions on the servers itself or if you can't access the server settings, you could try overwriting it through code:
ini_set('session.gc_maxlifetime', 6000000);
session.gc_maxlifetime manual
If you are unable to change the lifespan of sessions on the server, you could use this small code 'trick', keep in minde that if the clients pc shuts down or goes into sleep mode, the sessions will also expire:
Basicly you create a php script containing:
session_start();
Second you just write some jquery with the following code:
$(document).ready(function() {
// keep alive
setTimeout(keepalive(),120000);
});
function keepalive() {
$.get( "url/to/ajax.php", function( data ) { setTimeout(callserver,12000); });
}

You can use a trick, http://php.net/manual/en/function.session-start.php#example-5997
Starting with Php version 7.0 was added an option to prevent session expire. A time of 86400 means 1 days. You can adjust as you want.
if (session_status() == PHP_SESSION_NONE) {
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
session_start(['cookie_lifetime' => 86400,]);
} else {
session_start();
}
}
You can put at the top of Php files or include a file with this code on your project.
Hope this help.

Related

How to create logout without SQL and only PHP?

So far, I have only the login.html files which has login form, redirects user once logged on and logout function. What I want to do is once a user logs in, they redirect to but their username is displayed on the top of the page. And with the file... I just want it to be able to logout the user. So far on my website, I can login as far as I am concerned, and it redirects once user logs in, but I can login as many times as I want, and I can logout as many times as I want.... It's complicated to sort out and I want to do this without SQL or any other server-side storage (since I am only using HTML local storage).
You have to remove the session of username in logout code
unset($_SESSION['username']);
Hope this helps..If not,It would be better if you could provide the code, so that the problem can be sorted out
WRITE THIS ALL IN TOP PAGE
IN YOUR LOGIN PAGE
<?php
session_start();
if (isset($_POST["submit"])) {
$username = $_POST["username"];
$_SESSION["username"] = $username;
header('Refresh: 5; URL=GameWebsite.php')
}
?>
IN YOUR LOGOUT PAGE
if(isset($_SESSION['username']))
{
session_start();
session_unset();
session_destroy();
//Then you may redirect to the login page if you want after sometime.
echo " You have successfully logged out... You will be redirected back to the login page in a moment. ";
header('Refresh: 5; URL=login.php');
}
else
{
header("Location:login.php"); // HERE WHEN USER NO HAVE SESSION
}
IN ANOTHER PAGES YOU CHECK
if(isset($_SESSION['username']))
{
}else
{
header("Location:login.php"); // HERE WHEN USER NO HAVE SESSION
}
in your login page write on top
if(isset($_SESSION['username']))
{
header('Refresh: 5; URL=GameWebsite.html')
}
In your logout.php write
if(isset($_SESSION['username']))
{
session_start();
session_unset();
session_destroy();
//Then you may redirect to the login page if you want after sometime.
echo " You have successfully logged out... You will be redirected back to the login page in a moment. ";
header('Refresh: 5; URL=Login.html');
}
else
{
header("Location: login.php");
}

PHP login script in a separated file

I have been developing the following php script (+ sqlite database) to create a login for my web.
Up to now I had used just one PHP file, but now I want to use different files for login and protected contents, I mean, I used to have all my web in one file php (contents and password script were together) but now I want to detach it in different php files (one for the login, login.php, and other phps protected: index.php, calendar.php...)
I used this code to password-protect php content:
<?php require_once "Login.php"; ?>
but it doesn't seem to work: it displays the form to login next to the content I wanted to protect.
This is the php script I'm using as login.php:
<?php
$db = new PDO('sqlite:data.db');
session_start();
if (isset($_GET['logout'])) {
unset($_SESSION['pass']);
header('location: index.php');
exit();
}
if (isset($_SESSION['timeout'])) {
if ($_SESSION['timeout'] + 4 < time()) {
session_destroy();
}
}
if (!empty($_POST['pass'])) {
$result = $db->query("SELECT user,password FROM users");
foreach ($result as $row) {
if (password_verify($_POST['pass'], $row['password'])) {
echo "Welcome! You're logged in " . $row['user'] . "! <a href='index.php?logout=true'>logout</a>";
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['timeout'] = time();
}
}
}
if (empty($_SESSION['pass'])) {
echo '<form method="POST" action=""><input type="password" name="pass"><form>';
}
?>
MY QUESTION IS: How can I use my php script to protect different files?Is there any way to embed a logout link too?
One way is to store a token in session variables when a user logs in. Confirm the token is there on each page, if it isn't redirect the user to the login page. For example assert_login.php:
<?php
session_start();
if('' == $_SESSION['token']) {
header("Location: login.php");
exit();
}
?>
Then, in the PHP at the top of each of your pages:
<?php
require('assert_login.php');
?>
You can also clear the session variable on logout, logout.php for example:
<?php
require('assert_login.php'); // has session_start() already
$_SESSION['token'] = ''; // empty the token
unset($_SESSION['token']); // belt and suspenders
header("Location: login.php");
exit();
?>
I was also going through same issue & the way I solved it:
PSEUDO CODE:
PHP SESSION START
if(isset(GET(logout){
SetLogout();
die()}
$redirect=false
if not session[auth] exists
if SERVER REQUEST METHOD IS POST
$redirect=true;
if POST(username) && POST(pass) exists
Sanitize both of them & assign to $user& $pass
if user == "John" && $pass == "secret"
Go To SetLogin();
else{
Go To SetLogout();
echo "Wrong Username or Password"
drawlogin();
die();}
} //user pass comparing ends
} //Server method is NOT POST, so maybe it is GET.
//Do nothing, let the control pass to next lines.
}//SESSION(auth) does not exists, so ask user to login
else {
drawlogin();
}
//Post-Redirect-Get
if ($redirect)
redirect header to this same page, with 301
die()
// Secret Content here.
function SetLogin($user){
$SESSION(auth) = TRUE;}
function SetLogout($user){
if SESSION(auth) exists
unset($SESSION(auth))
redirect back with 301, without query string //shake ?logout
}
function drawlogin(){
echo all the HTML for Login Form
What it does is, it checks various things/variables, and if all passes, the control passes to Secret Content.
Save it as pw.php, & include it on top of any file you want to protect. Logout can be triggered by Logout
Note that this is just a pseudo code, typed on a tablet. I will try to update it with actual version. It is not checked for errors. Use all standard PHP Security precautions..

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

Unable to redirect using header(Location:)

I am unable to redirect from the login page of my site to the dashboard. When I try to login by giving the correct username and password it again shows me the login page, but when I access the dashboard of my site by url I can access it which proves that session has started.
Below is my code:
<?php
error_reporting(0);
session_start();
include_once '../db.php';
if(isset($_REQUEST['admsubmit']))
{
$result=executeQuery("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'],ENT_QUOTES)."' and admpassword='".md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES))."'");
// $result=mysql_query("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'])."' and admpassword='".md5(htmlspecialchars($_REQUEST['password']))."'");
if(mysql_num_rows($result)>0)
{
$r=mysql_fetch_array($result);
if(strcmp($r['admpassword'],md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES)))==0)
{
$_SESSION['admname']=htmlspecialchars_decode($r['admname'],ENT_QUOTES);
unset($_GLOBALS['message']);
header('Location: admwelcome.php');
}else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
}
else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
closedb();
}
?>
From my experience with PHP, the problem is you cannot redirect a user after the page buffer has been emptied. The problem is you must send the headers before anything else for them to be recognized. You script sends html data before sending the Location header that causes the user to redirect, that's why redirecting does not work.
To resolve this issue you must start the buffer at the first line of PHP code to prevent html data being sent, and empty it (if the buffer gets full, it will empty automatically) at the end of the file. You can also specify the buffer size in the config file.
To turn on output_buffering add the following line to your .htaccess file
php_flag output_buffering on
To start the buffer you use the ob_start() function (http://www.php.net/manual/ro/function.ob-start.php).
To empty the buffer in case it has not filled, you use the ob_end_flush() function (http://www.php.net/manual/ro/function.ob-end-flush.php).
Your code should be:
<?php
ob_start(); // start the page buffer so html data is not sent before the header
error_reporting(0);
session_start();
include_once '../db.php';
if(isset($_REQUEST['admsubmit']))
{
$result=executeQuery("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'],ENT_QUOTES)."' and admpassword='".md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES))."'");
// $result=mysql_query("select * from adminlogin where admname='".htmlspecialchars($_REQUEST['name'])."' and admpassword='".md5(htmlspecialchars($_REQUEST['password']))."'");
if(mysql_num_rows($result)>0)
{
$r=mysql_fetch_array($result);
if(strcmp($r['admpassword'],md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES)))==0)
{
$_SESSION['admname']=htmlspecialchars_decode($r['admname'],ENT_QUOTES);
unset($_GLOBALS['message']);
header('Location: admwelcome.php');
}else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
}
else
{
$_GLOBALS['message']="Check Your user name and Password.";
}
closedb();
}
ob_end_flush(); // empty the buffer and send the html code back to the browser
?>
I also use a redirect function so I can redirect more easily:
function redirect($to) {
header("Location: " . $to);
}
Now you can redirect like this (it seems far more easier to the eye):
redirect("admwelcome.php");
Please rate my answer as I am a new user and can't rate others just yet :-)
I had the same problem 2 minutes ago... Now is solved :)
Try using JavaScript. Remplace header location, in the php code
?>
<script type="text/javascript">
window.location ="http://www.sirobd.com/index.php";
</script>
<?php
try this code with meta. in content attribut, you can change the number, it's the time in second before the redirection
if(strcmp($r['admpassword'],md5(htmlspecialchars($_REQUEST['password'],ENT_QUOTES)))==0){
$_SESSION['admname']=htmlspecialchars_decode($r['admname'],ENT_QUOTES);
unset($_GLOBALS['message']);
echo '<meta http-equiv="Refresh" content="2;url=http://yourWebsite/admwelcome.php">';
}else{
$_GLOBALS['message']="Check Your user name and Password.";
}
Try adding:
session_write_close();
before the header call, and then add exit for good measure.
session_write_close();
header('Location: admwelcome.php');
exit;

php session lost after submitting form

The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.

Categories