PHP session not logging out / unset - php

I know this question has many duplicates, but I tried several of them and none of those have been answered.
Here is my code for logout.php:
<?php
session_start();
require './codefiles/dbhelper.php';
$dbh = new DbHelper();
$dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\'');
session_unset();
session_abort();
session_destroy();
$_SESSION = array();
unset($_SESSION['username']);
unset($dbh);
header('location:index.php');
?>
But the session variables are just too "stubborn" to be removed. Neither session values are being cleared not the session variables are being removed. Object $dbh is being unset but not $_SESSION['username'];
Another unrelated problem, despite I am setting the LoggedIn = 0, in my SQL query, it just stays as 1 in database. LoggedIn field is of type 'bit'. SessionID field is set to blank though.
Any solutions please?
EDIT:
Removed echo $dbh->error as it was unnecessary.
EDIT 2:
Added session_destroy() as suggested by Hossam Magdy.

<?php
include 'codefiles/dbhelper.php';
if(!isset($_SESSION['id']))
{
header ("Location: login_form.php");
}
else
{
session_destroy();
die('You have been logged out.<meta http-equiv="refresh" content="0;url=login_form.php">');
}
?>
This is basically the "Logout" structure.

I don't know why, but the code for destroying the sessions was somehow not working in logout.php. It worked in index.php and other files, but will all sorts of unpredictable behavior.
Found a workaround to circumvent the problem. The logout.php has code as below:
<?php
session_start();
$_SESSION['logout'] = TRUE;
header('location:index.php');
?>
And add this code to index.php:
# Implement logout functionality
<?php
session_start();
if(isset($_SESSION['logout']) && $_SESSION['logout'] == TRUE){
foreach($_SESSION as $var => $value){
unset($_SESSION[$var]);
}
session_destroy();
session_unset();
}
?>
It may not be a standardized solution, but the code works for me every time, with no unpredictable behavior.
Thanks everyone for sharing their ideas.

Try this
<?php
session_start();
require './codefiles/dbhelper.php';
$dbh = new DbHelper();
$dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\'');
echo session_status() . '<br />';
session_unset();
session_destroy();
echo session_status();
// header('location:index.php');
Let's see what session_status() says.
But on my projects unset && destroy work.

Related

Webmatrix session_destroy()

I have written a simple code for $_SESSION variable in the first php file:
<?php
session_start();
$_SESSION["name"] = "John";
?>
and in another php file to render this:
<?php
session_start();
echo $_SESSION["name"];
?>
But after that i used session_unset(); and session_destroy(); and after that i can't render any new $_SESSION variable nor the existing one. I am using Microsoft WebMatrix program and Chrome as main browser. Any suggestions? Thank you in advance.
That is because session_destroy(); destroys the current session and also sends a header to the browser to delete the session variable. In the same time the session is deleted on the server (in PHP) and the $_SESSION variables can no longer be used. You can always try to save the $_SESSION in another variable;
session_start();
$_SESSION['test'] = 'foo';
Next page:
session_start();
$saveSession = $_SESSION;
session_destroy();
var_dump($_SESSION); //Gives an empty array
var_dump($saveSession); //Still has ['test' => 'foo']
More information: http://php.net/manual/en/function.session-destroy.php and http://php.net/manual/en/book.session.php
Also, sidenote, you do not need to open and close PHP tags if they are combined;
<?php
session_start();
echo $_SESSION["name"];
?>
works just as well as
<?php
session_start();
?>
<?php
echo $_SESSION["name"];
?>

sessions value still showing on some pages after deleting the session

My sessions still shows values of sessions that are deleted on some pages. My header has the session start on every page.
<?php session_start(); ?>
I unset my session with:
$key_to_remove = $_POST['key'];
if (count($_SESSION["Carray"]) <= 1) {
unset($_SESSION["Carray"]);
} else {
unset($_SESSION["Carray"]["$key_to_remove"]);
sort($_SESSION["Carray"]);
}
Try This I use this kind of code for destroy session and it's working.
<?php
session_start();
$_SESSION = array();
session_destroy();
if(isset($_SESSION['key']))
{
unset($_SESSION['carry']);
}?>

Session is not maintained

I have a simple authentication: you login in the login.php page and you are redirected to the home.php page.
This is the code of login.php:
if(pg_num_rows($rs) == 0){ //I search in db for a row with username and password
$errMess = "error";
pg_close($conn);
}else{
$row = pg_fetch_row($rs);
session_start();
$_SESSION['username']=$_POST["nick"];
$_SESSION['admin'] = $row[0];
pg_close($conn);
header("Location: /home.php");
}
now in the home I have the header done in this way:
<?php require_once("scripts/functions.php");
require_once("scripts/config.php");
session_start();
?>
<div id="siteHeader" class="headersLeft"><?php echo WELCOME;?></div>
<div id="userContainer" class="headersRight">
Logged as: <?php echo getDisplayName(); ?>
<?php if(isset($_SESSION['username'])) {?>
<button class="button" onclick="location.href='/logout.php';">logout</button>
<?php }else{ ?>
<button class="button" onclick="location.href='/login.php';">login</button>
<?php }
?>
</div>
it doesn't work: even if data is correct it still gives me "guest", the session variable is lost in the header passage..how come?
Solved: i was under windows and the default path to the temp folder, where php actually saves session files, was wrong: was "/tmp" and was not recognized.
I set it to "C:\php\tmp" and it worked: session file was not saved at all!
Write session_start(); on top of everything (right after
<?php
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
or if still doesn't work then write your code like this:
<?php
ob_start();
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
Also don't forget to put these two lines at the top of your login.php page.
Hope it helps :)
I'm guessing there's some more code after the if statement that continues to manipulate $_SESSION. That's where $_SESSION['username'] is assigned the 'guest' value.
Remember, header("Location: /home.php"); only sets a response header. It doesn't redirect immediately, stopping script execution.
Place a exit; command right after header() to prevent execution from reaching the rest of the code:
header("Location: /home.php");
exit;
this works for me:
session_save_path ( "" ) ;
session_start();

PHP Session Unsets Itself

my session keeps getting unset, whenever I refresh a page, but when I made a control test it seemed to work fine.
Control(Held data):
<?php
session_start();
echo(var_dump($_SESSION));
$_SESSION['name'] = 'john doe';
?>
Top of index.php
<?php
session_start();
echo(var_dump($_SESSION));
include('utils/utils.php');
?>
Login page:
<?php
session_start();
include('utils.php');
if(isset($_POST['email']) && isset($_POST['password'])){
$email = filter($_POST['email']);
$password = getPwd(filter($_POST['password']));
if(!isset($_SESSION['email']) && !isset($_SESSION['password'])){
if(isAccount($email, $password)){
$key = genAuthKey();
$_SESSION['email'] = $email;
$_SESSION['auth_key'] = $key;
mysql_query("update `users` set `auth-key`= '$key' where `email`='$email'") or die(mysql_error());
print("ok");
}else {
print('error');
}
}else {
print('error');
logOut();
}
}else {
print('error');
}
?>
The code is getting fired, because it updated the auth-key in the table. I honestly have no idea what the issue is.
Also, the session is unset when I reload the index page.
I've got some more information. The pages can hold session data, and retain it, but once another page using session is loaded, it will unset all data.
Check if you use Unicode encoded PHP files with BOM.
PHP is not aware of the BOM. The BOM results in an output before your first <?php so PHP fails to set the related HTTP header for the session cookie.
From the docs:
To use cookie-based sessions, session_start() must be called before
outputing anything to the browser.

php session doesn't work

How it should work:
Index.php is the secured page. It includes check.php, which checks if you have a session = good. If it hasn't, you're not logged in -> log off, remove session. But it doesn't work, it always logs off, like I didn't log in...
index.php
include ‘check.php’;
echo "logged in";
check.php
session_start();
if($_SESSION[‘login’] != ‘good’) {
unset($_SESSION[‘login’]);
unset($_SESSION[‘name’]);
header(‘Location: login.php?logoff’);
exit();
}
Login.php
if(isset($_POST[‘login’])) {
$gb = array();
$gb[‘user1’] = ‘pass1’;
$gb[‘user2’] = ‘pass2’;
if(isset($gb[$_POST[‘username’]]) && $gb[$_POST[‘username’]] == $_POST[‘password’])
{
$_SESSION[‘login’] = ‘good’;
$_SESSION[‘name’] = $_POST[‘name’];
header("Location: index.php");
} else {
header("Location: login.php?wrongpass");
}
} else { ?>
Login Form
<?php } ?>
I hope someone can help me!
You should verify you started the session in login.php.
Put session_start(); in all the pages
You need to have session_start() at the top of all the pages, you havent shown the session start for your login page.
(Thanks to Danny for proving I cant type)
Check that you have register_globals is On in your php.ini
First check on the pages you want to use session variables session is start or not and if session is not stat then start it.
and this is the very first line in the php file.
Code for the session checking is :
if(!session_id())
{
session_start();
}
if($count==1){
session_start();
$_SESSION['Username'] = $UserName;
$_SESSION['Password'] = $password;
UpdateOnlineChecker($Session);
header( "Location: http://". strip_tags( $_SERVER ['HTTP_HOST'] ) ."/newHolo/" );
exit;
}
else {
echo "Wrong Username or Password";
}
Look at my code. It checks if the statement is true (for me, if there is one row with a query statement i execute). Then i start a session and basically Ill define global session variables, sned out a query to my database to update the session and then refer through.
you are missing a session_start(); in your if true block.
Use one for action document such as index.php there is code:
session_start();
if(isset($_POST['login']) && isset($_POST['password'])){
// login
header('Location: (here is some page)');
}
if(!isset($_SESSION['user']){
// #todo some action
} else {
require_once('login.php');
}
if(isset($_GET['logout'])){
unset($_SESSION['user']);
header('Location: (here is some page)');
}
I think problem is header:
('location:------.php);
Your hosting server doesn't run this.
You can use this:
echo "<script>window.location.href='-----.php'</script>";

Categories