How to change PHP session time in this code? - php

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

Related

stop session from logging user out

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.

How to authenticate securely by session tokens and cookies? updated

I tried to write my own authentication method (school project), and I'm stuck.
Please advise, how to solve a secure authentication:
There is an index.php which contains everything that needs to be "protected". I will copy the relevant parts of my code here.
updated index.php
session_start();
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['PHPSESSID'])){
if ($_SESSION['PHPSESSID'] == $_COOKIE['PHPSESSID']){
$authStatus = true;
}
}
return $authStatus;
}
if(!checkUserAuth()){
include_once(dirname(__DIR__).'/admin/authentication/login.php');
exit();
}
If the checkUserAuth() determines, that there is no properly authenticated user, will include the login.php and stop the rest of the script.
updated login.php:
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
$_SESSION['PHPSESSID'] = $_COOKIE['PHPSESSID'];
$_SESSION['login_user'] = $_POST['user'];
What I imagine that might happen, is that if the login details are correct, the login.php sets a cookie, and refreshes the page. Then the index.php will detect the cookie, and skip the login part.
The login is pretty much figured out, and thanks to Juned, I think it is working now. However I don't know how secure is this?
On a scale from 1 to very, how wrong I am?
There are loads of ways of doing this. The below pseudocode is not the most efficient but should work and I don't think what you've done above will actually work.
Does this help?
login.php pseudocode
<?php
session_start(); // this function checks if there's a session ID already set, if not, sets one.
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
// do your login details checking here
// if login details correct
// set a flag in the $_SESSION superglobal and whatever else you want to store about the user like their username e.g.
$_SESSION["loggedIn"] = true;
$_SESSION["username"] = "$_POST['user']"; // better practice to fetch a clean version from your database
//else return user to login page
}
?>
index.php pseudocode
<?php
session_start(); // this will fetch the session ID and other variables that you might have set e.g. username, logged in status
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true){
$authStatus = true;
}
return $authStatus;
}
if(!checkUserAuth()){
// redirect to login page. e.g.
header('Location: login.php');
exit;
}
?>

Why is if (empty($_SESSION['gebruikersnaam']['wachtwoord'])) not working?

first off all my English is not very good. Sorry I do my best. I am developing a CMS system. I need an inlog system for it. If you are not logged in you can't view some of the pages. I created a php session of it but it doesn't work on the other pages... I will include some off the code I wrote.
On the page I check the username and password, I created the session like this. And worked with session to check username and password, so it works on that page.
<?php
session_start();
$_SESSSION['gebruikersnaam'] = $_POST['gebruikersnaam'];
$_SESSSION['wachtwoord'] = $_POST['wachtwoord'];
if(($_SESSSION['gebruikersnaam'] == 'admin')
&& ($_SESSSION['wachtwoord'] == 'admin123')) {
include("adminpanel.php");
} else {
echo "Uw gebruikersnaam of wachtwoord is foutief.";
}
?>
On my other pages I added this to check if the user is logged in. I seem to never get that I am logged in and I can't echo the session out. Here is the code!
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
If the conditional statement with the session works, I can redirect the user to the log in page if he is not logged in.
Thanks in advance you would help me a lot!
That's because of a slip of the tongue, its $_SESSION not $_SESSSION and also:
$_SESSION['gebruikersnaam']['wachtwoord'];
Is actually referring to 1 value, not two:
$data = array('gebruikersnaam' => array('wachtwoord' => 'mijnwachtwoord'));
echo $data['gebruikersnaam']['wachtwoord'];
Instead do:
if(!empty($_SESSION['gebruikersnaam']) || !empty($_SESSION['wachtwoord'])){
echo "not ingelogd";
}
However, you should only store a username and id in a session. Storing the password is a potential security breach and is not necessary.
You could also use something like this to scan for required values:
function required_session_fields(array $keys){
foreach($keys as $k){
if(!array_key_exists($k, $_SESSION) && empty($_SESSION[$k])){
return false;
}
}
return true;
}
if(required_session_fields(['gebruikersnaam', 'wachtwoord'])){
echo 'gelukt';
}
If you started the session and included a file, you can still access the $_SESSION variable. On every new server request, make sure the session is started.
On the other pages you must have
session_start();
before
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
However this variable $_SESSION['gebruikersnaam']['wachtwoord'] is never created. Currently you have created $_SESSION['gebruikersnaam'] and $_SESSION['wachtwoord']
Perhaps you meant to have something like
if(!empty($_SESSION['gebruikersnaam']) && !empty($_SESSION['wachtwoord'])) {
echo "not ingelogd";
}

use php to display log in and log out link according to active session

This is the code i have at the moment but will not work, displays log out button when logged in only on one page then logs user out automatically ?
<?php
if(!session_is_registered(myusername))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
You had forgotten to do session_start() out of many things, and please make sure to share that, on every one of your pages, where you want to enable session protection.
<?php
session_start();
if(!isset($_SESSION['username']) && empty($_SESSION['username']))
{
echo '<b>Log In</b>';
}
else
{
echo '<b>Log Out</b>';
}
?>
session_is_registered is deprecated. Try using $_SESSION instead
if ($_SESSION["isLoggedIn"]) {
// Log out HTML goes here
} else {
// Log in HTML goes here
}
You'll need to include session_start() at the top of all of your files and you can set $_SESSION["isLoggedIn"] just like any other variable: $_SESSION["isLoggedIn"] = TRUE

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