Can you help me debug my session time out function? - php

Hi I am creating secure login functionality for my site. I have a function called sessionTimeOut() which i call at the top of each page of my site. As you can see within the function, if the user has been inactive for more than 30 mintues, I call a logOut() function and also a secure_session_start() function before redirecting the user back to the login page. I'm wondering will these functions execute fully before the redirect occurs? I'm not sure of the best way to debug the code. any help would be appreciated thanks.
function sessionTimeOut(){
//We implement a session timeout of our own. We use a simple time stamp that denotes the time of the last activity (i.e. request)
//and update it with every request
if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
//last request was more than 30 minutes ago
logOut();
//start a new secure session so that we can create a new session variable.
secure_session_start();
//create a session variable to say that the login session has timed out after redirecting to the login page.
$_SESSION['loginTimedOut'] = true;
header('Location: login.php');
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); //update last activity time stamp
//Now we also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions
if(!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
}else if(time() - $_SESSION['CREATED'] > 1800) {
//session started more than 30 minutes ago
session_regenerate_id(true); //change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); //update creation time
}
}
logout() function:
function logOut(){
//Unset all session values
$_SESSION = array();
//get session parameters
$params = session_get_cookie_params();
// Delete the actual cookie.
setcookie(session_name(),
'', time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]);
// Destroy session
session_destroy();
}
function secure_session_start() {
/* This is a function to start a PHP session in a secure way.
* This function stops crackers accessing the session id cookie through JavaScript (for example in an XSS attack).
* Also the session_regenerate_id() function, which regenerates the session id on every page reload, helps prevent session hijacking
*/
$session_name = 'secure_session_id'; // Set a custom session name
$secure = false; //set to true if https
//This stops JavaScript being able to access the session id.
$httponly = true;
//Forces sessions to only use cookies.
if(ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
//Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
//Sets the session name to the one set above.
session_name($session_name);
session_start(); //Start the PHP session
session_regenerate_id(true); //regenerate the session, delete the old one to prevent session fixation attacks.
}

Related

How to Start custom session function inside a class

I am learning php.
I have a class and a function to start a custom session like the following,
Now how can I use the said custom session_start in every php page?
please help.
my code is like
<?php
// myclass.php
class abcd{
function sec_session_start() {
$session_name = 'sec_session_id'; // I have Set a custom session name
$secure = false;
$httponly = true;
if (ini_set('session.use_only_cookies', 1) === FALSE) {
$err='Could not initiate a safe session (ini_set)';
$err = Encryption::encode($err);
header("Location: ../login.php?error_msg=".$err);
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
//session_set_cookie_params(time()+3600,
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start();
session_regenerate_id(true);
}
}
?>
In this case the following error is showing :
Notice: A session had already been started - ignoring session_start()
myphp page is below -
<?php
// mypage.php
include_once "myclass.php";
$mevalue = new abcd;
$mevalue->sec_session_start();
code code code
?>
Please help me to solve this.
A session should last throughout the page visit and not be renewed on each page,
e.g. a user logs in once and this is stored into a session so the user doesn't need to login again for each new page or click.
Mostly a session starts if someone visits your page and remains until the user leaves the page -> closing the session.
The best way is to check if a session is open for this user and only start a session if the user doesn't have one.
To close a session one can use
session_write_close ( void ) : bool
Source
With this you can update your code to have a get_session function. In this function you can check if a session exists and use that one, if not start a new one
class abcd{
function init_session()
{
if (!isset($_SESSION)) {
$this->sec_session_start();
}
}
function sec_session_start() {....
And in your page
$mevalue->init_session();

Trouble in destroying session

I am having trouble in destroying session when user logout of its account. After logging out when i browse any page which is restricted to user not to access before login i can access that but if i close my browser after logging out and then try to access the page i cant. Please solve my problem so that user cannot access the pages after logging out even he/she has not closed the browser. Here's my code of logging out and destroying session.
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
if(isset($_POST['logout'])){
session_start();
// Unset all of the session variables.
$_SESSION = array();
$_SESSION["Alogin"] = "";
// If it's desired to kill the session, also delete the session
cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
}
?>
Session session_start() must be at the top
<?php
// Initialize the session.
session_start();
// If you are using session_name("something"), don't forget it now!
if(isset($_POST['logout'])){
//What ever you want
// Finally, destroy the session.
unset( $_SESSION );
session_destroy();
//redirect to loginpage
header('Location:../login.php');
exit;
}
?>
Put your session_start (); outside the if statement and
check with print_r ($_POST); if you send $_POST['logout']

How to delete session of The HTTP_USER_AGENT

In order to increase the security for the logged-in users, after the session_start(); and assigning the other session variables, I also try to store the HTTP_USER_AGENT value, using $_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']); for the login.php page.
Besides, in the login.php page, I redirect logged-in users to the home page if they try to visit it again without logging it out first, using the conditional like this:
if (isset($_SESSION['agent']) OR ($_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']) ) ) {
//redirect to home page
header('location:http://index.php.com');
exit();
}
The question is that in my logout.php page I code the conditional like this:
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT']) ) ) {
//Redirect to home page
}else{
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session itself.
setcookie (session_name(), '', time()-3600); // Destroy the cookie.
}
Then I came back to visit the login.php page again as a logged-in user (session has been set), it still redirected me to the home page.
Then I tried deleting the cookies in the FF browser, close it, then revisited the login.php page, it still redirected me.
Do you know what I was wrong or missing?
NOTE: I have no problem to destroy the session if not storing **the HTTP_USER_AGENT
You have an assignment where you want to check.
Change:
if (isset($_SESSION['agent']) OR ($_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']) ) ) {
to
if (isset($_SESSION['agent']) OR ($_SESSION['agent'] == md5($_SERVER['HTTP_USER_AGENT']) ) ) {
off topic security tip(maybe helpfull):
public function Start_Secure_Session()
{
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params
$cookieParams = session_get_cookie_params();
// Set Cookie Params
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $this->isHTTPS, $this- >deny_java_session_id);
// Sets the session name
session_name($this->session_name);
// Start the php session
session_start();
// If new session or expired, generate new id
if (!isset($_SESSION['new_session']))
{
$_SESSION['new_session'] = "true";
// regenerate the session, delete the old one.
session_regenerate_id(true);
}
}

PHP session_set_cookie_params break php session_start() function and $_SESSION variable

I'm trying to create a secure session by creating start_secure_session() function like this:
function start_secure_session() {
$session_name = 'secure_session';
$secure = true;
$httponly = true;
if (ini_set('session.use_only_cookies', 1) === false) {
die('error');
}
$cookie_params = session_get_cookie_params();
session_set_cookie_params($cookie_params["lifetime"],
$cookie_params["path"],
$cookie_params["domain"],
$secure,
$httponly);
session_name($session_name);
session_start();
session_regenerate_id(true);
}
The problem is, start_secure_session() is not saving $_SESSION super global variable. It's unset immediately when the page refreshed. It works only if I comment this out:
//$cookie_params = session_get_cookie_params();
//session_set_cookie_params($cookie_params["lifetime"],
// $cookie_params["path"],
// $cookie_params["domain"],
// $secure,
// $httponly);
or in other words, not setting a custom cookie params.
What should I do to make it works? So, the session_start() can work properly and $_SESSION variable can remember it's value?
I think it is because of the secure=TRUE and you not using HTTPS?
It will not create a session on a non-secure connection with secure set to TRUE.

Session variables not carrying to next page

I've just begun using sessions and am having some headaches, I had this working last night, now opening it today...no longer works.
In my login processor I have the following if everything is OK. This script works fine, I have echoed the session variables to ensure that the array works, and it does.
$username - > post from login script
$encrypt_password -> created from password check further up the script
{
$session_name = 'LOGIN'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
$cookie_lifetime = '3600';
$cookie_path = '/';
$cookie_domain = '127.0.0.1';
session_set_cookie_params($cookie_lifetime, $cookie_path, $cookie_domain, $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
$group = $row['group_type'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; /*grabs browser info*/
$user_id = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); /*XSS Protection*/
$group_id = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $group); /*XSS Protection*/
session_start();
$_SESSION['user']=$user_id;
$_SESSION['group_name']=$group_id;
$_SESSION['login_string'] = hash('sha512', $user_browser.$encrypt_password);
session_write_close();
header("location:".$group_id."_index.php");
}
I have created an include file which gathers the info from the session, included on every protected page, this is where it fell apart. I have created custom error codes for each if statement and have found that the if statement here fails. Echoing the session variables or evening printing the session array returns nothing.
$session_name = 'LOGIN'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
$cookie_lifetime = '3600';
$cookie_path = '/';
$cookie_domain = '127.0.0.1';
session_set_cookie_params($cookie_lifetime, $cookie_path, $cookie_domain, $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(false); // regenerated the session, delete the old one.
if(isset($_SESSION['user'],$_SESSION['group_name'], $_SESSION['login_string']))
I was changing around the way the user groups worked before this broke, however none of the variables make it through. I am learning from his tut by the way: create a secure login script in php and mysql
Also do I need to call the session parameters every time a user visits a protected page?
Thanks in advance for any pointers.
Try putting session_start(); on TOP of everything, most importantly before you're calling a session. You're calling session_name($session_name); before it even started.
it=session
your regenerating the session on every page, which causes the previous session to destroy data.
remove session_regenerate_id(false);

Categories