I am new to learning Php. I have created the following code.
<?php
/*
* Testing Sessions with PHP
*/
session_start();
$_SESSION['user_id'] = 'Testing User';
session_destroy();
?>
<html>
<head>
<title> Sessions Page</title>
</head>
<body>
<?php
echo $_SESSION['user_id'];
?>
</body>
</html>
Now the echo $_SESSION['user_id'] echos testing user. In my opinion it should not, as i have destroyed the session. what is the reason?
You need to unset the session vars.
See http://php.net/manual/de/function.session-unset.php
Means, put session_unset() before you destroy the session.
The function session_destroy() will indeed destroy your session. The session is in this case the file (or db) on the server, holding your data. That means you cannot access this session on other pages afterwards.
The globale $_SESSION[] variable is a different story. It is filled from the session file, before the code on your page starts processing. Therefore it holds a copy of the data and stays in memory until your page has finished processing. You can clear this variable with session_unset(), but as well you can wait until the page has finished and all it's variables are destroyed anyway.
This appears to be (for whatever reason) by design. The correct way to do what you wish is.
session_start();
$_SESSION['user_id'] = 'Testing User';
session_unset();
session_destroy();
This code will remove all session variables from $_SESSION and then destroy the session.
Need to be more comprehensive as PHP sessions can really behave differently.
The following works perfectly in all browsers to kill/destroy/unset all session info. Perfect to be used in sign-out file.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>
Related
There are two login pages and if one page is logged out other also automatically getting logged out how to change that?
adminlogout.php
<?php
session_start();
unset($_SESSION['ADMIN_UNAME']);
session_destroy();
header("location: adminlogin.php?logout=true");
?>
logout.php
<?php
session_start();
unset($_SESSION['SESS_MEMBER_ID']);
session_destroy();
header("location: login.php");
?>
Please remove session_destroy() function. session_destroy() delete complete session information for request with sessionid from the server. Hence both scripts logouts.
adminlogout.php
<?php
session_start();
unset($_SESSION['ADMIN_UNAME']);
header("location: adminlogin.php?logout=true");
?>
logout.php
<?php
session_start();
unset($_SESSION['SESS_MEMBER_ID']);
header("location: login.php");
?>
When you use session_destroy(); you completely remove everything the server knows about your current session. Note a session survives while the current browser instance is open, if you destroy the session you destroy all the session globals.
If you want to logout of just the admin or a normal user you should just change a session variable to reflect that.
As the others already pointed out, the problem is the call of session_destroy() as this destroy the whole session.
But I'd like to add that you should maybe consider using a multidimensional array in your session for different purposes or, what is even better, use different sessions as they are in completely different areas (e.g. the admin session should definitely not be shared with a normal user session, using HTTPS cookies, etc.).
unset the session variable or make the session variable as empty in logout.php
adminlogout.php
<?php
session_start();
$_SESSION['ADMIN_UNAME']='';
header("location: adminlogin.php?logout=true");
?>
logout.php
<?php
session_start();
$_SESSION['SESS_MEMBER_ID']='';
header("Location:login.php");
?>
I am newbie in php. I can not under stand a thing that session variable is outputting even after session_destroy() and session_unset().Here is my simple code for test
`session_start();
SESSION['name']='sovon';
session_destroy();
session_unset($_SESSION['name']);
echo $_SESSION['name'];
`
The output is 'sovon'. My question what is session_destroy() and session_unset() doing here and whats the difference between them?
Oh! when I am deleting session_destroy() that variable is getting unset. why?
I got it faisal, session_distroy is destroying session if its created in other pages. If the session variable created on the same page then it will be remain. The best practice is to null the session variable after session distroY $_SESSION = NULL;
Like I am using in logout,
session_start();
session_distory();
$_SESSION = NULL;
header('Location: Login.php');
I think this help you.
Perhaps its easier if you read the php manual.
session_destroy()
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
So if you want to unset the data inside. You have to unset it.
unset($_SESSION);
Session unset...
session_unset()
deletes all variables and leave session_id. But session_unset has no parameters.
What you search is
unset($_SESSION['name']);
The following works perfectly in all browsers to kill and destroy and unset all session info. Perfect to put it in sign-out file.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>
sorry for a repetitive question, I've seen a few of these on this forum but none of the responses worked for me...
I am building a basic login using php sessions, which I'm new at...
login.php validates html login form and begins a session, setting variables: $_SESSION['login'] and $_SESSION['id],
then each page that requires a valid login uses require 'session.php'; which checks the $_SESSION['valid'] variable and redirects a user w/o proper login variable. The problem is when I logout neither session variable I've set will unset.
Right now my logout.php file uses about every method to destroy the variables that I've been able to find online and none will actually do it.
So whenever I log out, I can still access the 'private' pages.
Also note: I have tried it w/o a session name ex: session_start(); that didn't work so now I'm using session_start("user");
Also note: I am NOT using cookies.
Here are the files I mentioned:
login.php
$email=$_POST['email-log']; $pass=$_POST['password-log'];
$i=-1;
do
{$i++; $path="users/".$i.".json";
$file= file_get_contents($path);
$x=json_decode($file,true);
} while($x['email']!=$email);
$id=$i;
$truepass=$x['pass'];
$errors=0;
$hash=hash('sha256',$pass);
if($hash != $truepass){$errors=$errors+1;}
if($errors==0){
session_start("user");
$_SESSION['login']="valid";
$_SESSION['id']=$id;
header('Location: loginlanding.php');}
else{header('Location: front.php?error=y');}
session.php
session_start("user"); if($_SESSION['login'] !== "valid") {header('Location: front.php?needto=login');}
logout.php
unset($_SESSION); unset($_SESSION['login']); unset($_SESSION['id']); session_unset("user"); $_SESSION=array(); session_destroy("user"); header('Location: front.php?logged=out');
Any and all responses are welcome and I thank you in advance, also note, I am new to logins in general so any advice to beef up security is welcome also. I'm planning on making it more secure, but first I need to get this basic functionality up and running.
You should never unset($_SESSION).
The easiest way to clear the $_SESSION variable is $_SESSION = Array();
However, you can also iterate with unset:
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
It's amazing how many things you're attempting to do after you've unset the only reference you had to the session in the first place. Directly from the manual:
Caution
Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.
http://php.net/manual/en/function.session-unset.php
You're unsetting $_SESSION so your unsets to the other arrays of the super global $_SESSION aren't registering, leaving them still in the browsers temporary cookies. Use session_unset() instead if you're trying to remove all session variables. Otherwise, don't unset the session global, but unset each individual value of it you want to remove.
My working example (notice that you must put start on the call)
<?php
session_start();
session_unset();
session_destroy();
header('location: ./');
?>
I tried to destroy all session variable by using the session_destroy() method, but after using this method, the values are not destroyed.
Why is session_destroy() not working?
Is there any other way to destroy the session in PHP?
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
{
session_destroy();
session_unset();
}
Perhaps is way too late to respond but, make sure your session is initialized before destroying it.
session_start() ;
session_destroy() ;
i.e. you cannot destroy a session in logout.php if you initialized your session in index.php. You must start the session in logout.php before destroying it.
After using session_destroy(), the session is destroyed behind the scenes. For some reason this doesn't affect the values in $_SESSION, which was already populated for this request, but it will be empty in future requests.
You can manually clear $_SESSION if you so desire ($_SESSION = [];).
If you need to clear the values of $_SESSION, set the array equal to an empty array:
$_SESSION = array();
Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.
Try the following:
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
I had to also remove session cookies like this:
session_start();
$_SESSION = [];
// 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();
Source: geeksforgeeks.org
Actually, it works, but you also need to do $_SESSION = array(); after the session_destroy to get rid of $_SESSION variables. However, avoid doing unset($_SESSION) because that makes sessions useless.
Well, this seems a new problem for me, using a new php server. In the past never had an issue with sessions not ending.
In a test of sessions, I setup a session, ran a session count++ and closed the session. Reloaded the page and to my surprise the variable remained.
I tried the following suggestion posted by mc10
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
However, that did not work. I did not think it could work as the session was not active after destroying it, so I reversed it.
$_SESSION = array();
session_destroy();
That worked, reloading the page starting sessios and reviewing the set variables all showed them empty/not-set.
Really not sure why session_destroy() does not work on this PHP Version 5.3.14 server.
Don't really care as long as I know how to clear the sessions.
session_destroy() is effective after the page load is complete. So in the second upload, the session is terminated. But with unset() you can also log out from within the page.
if you destroy the session on 127.0.0.1 it will not affect on localhost and vice versa
It works , but sometimes it doesn't (check the below example)
<?php
session_start();
$_SESSION['name']="shankar";
if(isset($_SESSION['name']))
{
echo $_SESSION['name']; // Outputs shankar
}
session_destroy();
echo $_SESSION['name']; // Still outputs shankar
Weird!! Right ?
How to overcome this ?
In the above scenario , if you replace session_destroy(); with unset($_SESSION['name']); it works as expected.
But i want to destroy all variables not just a single one !
Yeah there is a fix for this too. Just unset the $_SESSION array. [Credits Ivo Pereira]
unset($_SESSION);
Add session_start(); before !Doctype Declaration
<?php session_start(); ?>
<!doctype html>
<html>
<body>
<?php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
{
session_destroy();
session_unset();
}
?>
</body>
</html>
My website doesn't start a session when I visit, I don't know why but my website works like this:
<?php
session_start();
$title = "Home";
include("include/header.php");
include("include/functions.php");
?>
...HTML stuff here...
<?php
include("footer.php");
?>
But when I check with Cookies (add-on for Firefox) there are no sessions started... I used session_regenerate_id(); but it doesn't work at all.
It fails to log in since there are no sessions, I do not have any session_destroy() in my website, only in the logout.
But funny thing is, when I login (without refreshing or navigating just yet) and then click on the logout button, there is a session on my website, then when I log in again, it tells me that I am logged in BUT if I login and navigate or refresh, it doesn't tell me that I'm logged in since there are no sessions...
Logout:
<?php
session_start();
session_destroy();
setcookie("cookie-name", "", time()-60, "", "", 0);
header("Location: ../index.php");
exit;
?>
What do I do?
You must have session_start() at the beginning of every file that is being accessed and uses sessions. The name is misleading, session_start() actually doesn't start a new session but initialzes PHP session menagment.
Not sure if it's related, but there was a strange PHP quirk that required the SESSION_START() to be on the line immediately below the <?php tag. Something about whitespace and extra things above the session used to make it go haywire for me. I've been using Zend of late, which avoids that issue with its own session handling system.
You might try doing a print_r($_SESSION) to see if there's anything in the session array at all.
It's probably because you are not setting a session in either of the examples you have given, you have to have a line like the one below to actually create a session, and then to access the session variables on all subsequent pages you need session_start();
$_SESSION['example'] = 'something';
It doesn't look like your setting anything in the session or the cookie.
If you want to pass information around in the session you'll need to assign the necessary values in the $_SESSION variable.
For example on your main page you can do:
<?php
session_start();
$_SESSION['myVariable'] = "my text";
?>
And then on any subsequent pages you can access the variable you've set.
<?php
session_start();
echo $_SESSION['myVariable']; //This will print "my text"
?>