Destroy session in php [duplicate] - php

This question already has answers here:
Why Session object destruction failed
(4 answers)
Closed 8 years ago.
i ve seen so many questions about this and im still having problems with that... can someone give me a help?
login page :
<?PHP
header("Content-Type: text/html; charset=utf-8");
$login = "root";
$senha = "test";
session_start();
session_set_cookie_params(0);
if ($_POST['login'] && $_POST['senha']) {
if ($login == $_POST['login'] && $senha == $_POST['senha']) {
$_SESSION['login'] = $login;
$_SESSION['senha'] = $senha;
Header("Location: index.php");
} else {
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header("Location: login.php");
}
}
?>
logout page :
<?php
session_start();
$_SESSION = array();
unset( $_SESSION['login'] );
unset( $_SESSION['senha'] );
setcookie(session_name(), '', time() - 3600, '/');
session_destroy();
Header("Location: login.php");
exit();
?>
im getting this error:
PHP Warning: session_destroy(): Session object destruction failed in \\N\Users\cPanel\gil\public_html\gilberto\logout.php on line 11

This is my usual approach, see the comments for further details.
session_start();
// 1. unset all of the session variables
$_SESSION = array();
// 2. delete the session cookie
if ( ini_get( 'session.use_cookies' ) ) {
$params = session_get_cookie_params();
setcookie( session_name(), '', ( time() - 42000 ), $params['path'], $params['domain'], $params['secure'], $params['httponly'] );
}
// 3. destroy the session.
session_destroy();

You don't have to make $_SESSION = array();
Just use session_destroy() like said here :
http://www.php.net/manual/fr/function.session-destroy.php

Here is a function i use to logout:
function logout(){
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
if(strtoupper($name) == 'PHPSESSID'){
continue;
}
setcookie($name, '', time()-360000);
setcookie($name, '', time()-360000, '/');
}
foreach($_SESSION as $key => $val){
unset($_SESSION[$key]);
}
header('Location: account/login');
die;
}

Related

Why count($_COOKIE) > 0 returns 'true' case while all cookies are deleted?

I am trying to delete a cookie by setting that cookie in past time:
$cookie_name = "user";
$cookie_value = "david";
//subtraction from time causes deletion of cookie
setcookie($cookie_name, $cookie_value, time() - (86400 * 30), "/");
With the below code I try to check whether cookie is enabled or not and it returns if case rather than else part, while I already dell that cookie:
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
But the else part is not working when we delete cookie and I don't know why?
The main problem is you just set user cookie time to past date not all the other cookie in super global $_COOKIE array . Try like this way to set for all $_COOKIE value using foreach() to past date and then check count condition.
<?php
$cookie_name = "user";
$cookie_value = "david";
$past_time = time() - 3600;
//use look set all cookie time to past date.
foreach ( $_COOKIE as $key => $value )
{
setcookie( $key, $value, $past_time, '/' );
}
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
?>
DEMO: https://3v4l.org/jvRXW

Session ID cannot be deleted

I am trying to create a login system. At the moment everything seem to be working as expected except I am not able to clear my session ID,
why do session_unset() and session_destroy don't seem to have any effect ?
UPDATE: solved below
INDEX.PHP
session_start();
if (array_key_exists('id', $_COOKIE) && $_COOKIE ['id']) {
$_SESSION['id'] = $_COOKIE['id'];
print("SESSION ID");
print("<br>");
print_r($_SESSION);
print("<br>");
print("COOKIE");
print("<br>");
print_r($_COOKIE);
}
// SET SESSION
function setSession($setSessionData) {
$_SESSION['id'] = $setSessionData[0];
if ($setSessionData[1] == 'yes') {
setcookie('id', $setSessionData[0], time() + 60*60*24*365, '/' );
}
};
// CLEAR SESSION
function unSetSession() {
session_unset();
setcookie("id", "", time() - 60*60*24*365, '/');
session_destroy();
}
SOLVED:
Had to initialise the session in my function called via Ajax; so the logout function is like so:
function unSetSession() {
session_start();
$_SESSION = array();
setcookie("id", "", time() - 60*60*24*365, '/');
session_destroy();
}

Session doesn't save when headering to another page

I've got a 'shoppingcart' page and if they modify any values there and then click on 'order' i want the session to actually store the information before i header to the next page, however it seems that the $_SESSION variable does not save it before starting.
I have tried the following:
Solution 1:
$_SESSION['winkelwagen'] = $winkelwagen;
session_write_close();
header("Location: checkout.php");
Solution 2:
$_SESSION['winkelwagen'] = $winkelwagen;
header("Location: checkout.php");
exit();
However, neither of these seem to work for me, i have tried looking at the following stackoverflow topics too:
PHP: session isn't saving before header redirect
Header Not Working With Sessions
however neither of these work, this is my code:
$header = false;
if(isset($_POST['moveForward'])) {
foreach($winkelwagen as $key => $val) {
if (isset($_POST['aantal' . $val['artnr']])) {
if (isset($_POST['verpakking' . $val['artnr']])) {
$verpakking = $_POST['verpakking' . $val['artnr']];
$aantal = intval($_POST['aantal' . $val['artnr']]);
if ($val['amount'] !== $aantal) {
$val['amount'] = $aantal;
$winkelwagen[$key]['amount'] = $aantal;
}
if ($val['verpakking'] !== $verpakking) {
$val['verpakking'] = $verpakking;
$winkelwagen[$key]['verpakking'] = $verpakking;
}
$header = true;
}
}
}
$_SESSION['winkelwagen'] = $winkelwagen;
session_write_close();
if($header) {
header("Location: checkout.php");
exit();
}
}
Any help would be appreciated!

How to set Session Timeout in php?

I'm still new in PHP language and trying out on how to set Session Timeout, which ensure that when user log in to their account, it will limit to few minutes / 1 hour before the account got logout automatically when user log in too long. I refered to this link.
http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
index.php
<?php
if(!isset($_SESSION))
{
session_start();
}
$timeout = $_SERVER['REQUEST_TIME'];
/**
* for a 1 minute timeout, specified in seconds
*/
$timeout_duration = 60;
if (isset($_SESSION['LAST_ACTIVITY']) && ($timeout - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
session_unset();
session_destroy();
session_start();
}
$_SESSION['LAST_ACTIVITY'] = $timeout;
?>
coupon.php
<?php
// error_reporting(E_ALL); ini_set("display_errors", 1);
session_start();
$timeout = 60; // Number of seconds until it times out.
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
}
}
// Update the timeout field with the current time.
$_SESSION['timeout'] = time();
// include ('sessionTimeout.php');
if( !isset($_SESSION["loginSuccess"]) ){
echo "<script type='text/javascript'>alert('Login failed!');</script>";
die('<meta http-equiv="refresh" content="0;URL=\'login-redirect.php\'" />');
}
?>
sessionTimeout.php
<?php
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if(!file_exists($path)) {
if(!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start_timeout(60, 10);
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
?>
logout.php
<?php
session_start();
include('config.php');
foreach($_SESSION as $key => $value){
if (strpos($key, $PROJECT_NAME) !== FALSE){
unset($_SESSION[$key]);
}
}
$_SESSION[$PROJECT_NAME . 'logout'] = true;
session_destroy();
//print_r($_SESSION);
header('Location:' . $base_url . 'index');
?>
Am i missing out something? This is because my session timeout doesn't work.
Start a Javascript timer when the page loads and redirect the user to the logout page when the timer expires.
<script type="text/javascript">
setTimeout(function() { window.location.href = "logout.php"; }, 60 * 60 * 1000);
</script>

is structure of code causing undefined $_SESSION variables?

When I navigate to a page which is locked (in other words when the box which states you have to Continue appears, I am getting undefined $_SESSION variables. Before I included the if (allowed_in()=== "Allowed"){ statement, I was not getting any undefined $_SESSION variables but as now need that if statement, Im starting to get those variable errors.
For the $_SESSION undefined errors, is it because I am placing the $_SESSION variables in the wrong place?
Below is an example QandATable.php order of code looks like:
<?php
ini_set('session.gc_maxlifetime',12*60*60);
ini_set('session.gc_divisor', '1');
ini_set('session.gc_probability', '1');
ini_set('session.cookie_lifetime', '0');
require_once 'init.php';
//12 hours sessions
session_start();
include('steps.php'); //exteranlised steps.php
?>
<head>
<?php
if (isset($_POST['id'])) {
$_SESSION['id'] = $_POST['id'];
}
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
?>
</head>
<body>
<?php
//once session is expired, it should log the user out, but at mo this isn't happening
if ((isset($username)) && (isset($userid))){ //checks if user is logged in
if (allowed_in()=== "Allowed"){
//QandATable.php code:
}else{
$page = allowed_in()+1;
?>
<div class="boxed">
Continue with Current Assessment
<?php
}
}else{
echo "Please Login to Access this Page | <a href='./teacherlogin.php'>Login</a>";
//show above echo if user is not logged in
}
?>
Below is the full steps.php:
<?php
$steps = array(1 =>'create_session.php',2 => 'QandATable.php',3 => 'individualmarks.php',4 => 'penalty.php',5 => 'penaltymarks',6 => 'complete.php');
function allowed_in($steps = array()){
// Track $latestStep in either a session variable
// $currentStep will be dependent upon the page you're on
if(isset($_SESSION['latestStep'])){
$latestStep = $_SESSION['latestStep'];
}
else{
$latestStep = 0;
}
$currentStep = basename(__FILE__);
$currentIdx = array_search($currentStep, $steps);
$latestIdx = array_search($latestStep, $steps);
if ($currentIdx - $latestIdx == 1 )
{
$currentIdx = $_SESSION['latestStep'];
return 'Allowed';
}
return $latestIdx;
}
?>
session_start() must go before any content.
Note:
To use cookie-based sessions, session_start() must be called before
outputing anything to the browser.
http://php.net/manual/en/function.session-start.php

Categories