I have read many related question here but seems not solve my problem. How to destroy session in PHP when user clicked at the browser back button.
Example, current page is home.php, when back button is clicked, it will go to index.php. So should be session will by destroy.
I trying both options. But still not destroy the session.
First Option (home.php)
<?php
session_start();
if (isset($_SESSION)) {
session_destroy();
}
?>
Second Option (index.php) This is not practical.
<script language="javascript" type="text/javascript">
window.history.forward();
</script>
If you want a reliable way to clear all values of any current session you can use this on the loading of any page where you want to remove session data:
<?php
session_start();
if ($criteria_for_session_deletion === true) {
$_SESSION = []; // _SESSION is now an empty array
}
This will remove any value from the superglobal. It will not change the identity of the superglobal, but that shouldn't be important if the variable is now empty.
It is unclear from your question but you may be having overlap issues with browser caching of the outputted HTML page. Please clarify exactly what you're trying to delete?
Clicking on a "back button" is a very problematical way of solving this concept and we really need some clarification from you as to what's actually going on.
If you have a user who needs to have session data removed then you should check this in PHP on a script before any outout is sent to the browser, and then triggering the above code when required.
You maybe should have a "validity check" script included in each page so every time one of these pages is loaded your "check script" is called, and deletes the session data when the deletion criteria is met.
Why do you want to destroy session? That is just irritating. I have seen such implementations in government/bank websites and it pretty much sucks.
Rather you should redirect the user to dashboard if the user is logged in.
This doesn't directly answer OP's question but is a better way.
Something like this:
if (isset($_SESSION)) {
header('Location: <dashboard-page>');
exit;
}
Related
I have implemented session into my application, but I need to allow the logged in user to use the back button to go to the previous pages.
How do I make sure that the session does not expire and allows the user to view the previous page?
Here is my code
<?php
//Start session
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$User = $_SESSION["User"];
//Page content
?>
I have started the session, when I use the back button on browser I get a page that reads session has expired. Which I do not want to happen.
in your php at the top of each page, start your session before your opening <html> tag
<?php session_start(); ?>
<html>
in your php somewhere set your session variables note this value must be serializable
<?php $_SESSION["variable"] = "value"; ?>
then anytime you want to access that session variable you can do the following AFTER calling session_start();
<?php echo $_SESSION["variable"]; ?>
if you handle your sessions in this manner, session variables will be available on previous and future pages.
caveat:
depending on browser and headers sent from your server, when you go back a page, it reloads the page as it was in the cache so consider the following:
User goes to page and is does not have a session variable set
User does action that sets a session variable and sends them to a second page
User hits back button
User is shown the pre-session cached version of the first page
User refreshes page
User now sees the first page w/ session variable set
the reason for the hiccup is that some browsers do not always make a new request on back button sometimes it loads from the browser cache. read the very end of this answer: https://stackoverflow.com/a/1313941/884453
EDIT
You posted code above with a check to session_status first. This is incorrect. You ALWAYS need so session_start();
<?php
//Start session
session_start();
// User is either pulled from the session or is null
$User = $_SESSION["User"] ? !empty($_SESSION["User"]) : NULL;
//Page content
?>
the code for if (session_status() !== PHP_SESSION_ACTIVE) { is only useful in situations where some other bit of code (usually in a framework) may have started the session already.
If you have set up your session management correctly, you don't need to do anything.
However, this correctly depends on what kind of state you have in the session and how you manage it. Also timeouts will still apply (as they should).
You can use javascript history method also for that so your session also remain same.
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script>
I'm trying to understand sessions and how some of the functions to end them work.
I've gone to different sites/and even here on SO and, well essentially, nothing is working.
I have an app I'm trying to work on and when the user logs in, I store the username like so
(not going to paste the whole code but you get the idea)
if($row == 1){
session_start();
$_SESSION['usrname'] = $login_usrname;
$_SESSION['usrpass'] = $login_usrpass;
header("Location:index.php");
exit;
}
On the index page of said app I have a check like so
session_start();
if(!isset($_SESSION['usrname']) && !isset($_SESSION['usrpass'])){
header("Location:login-acc.php");
exit;
}
And it lets them in. I check the cookies in firefoxes web dev tools and I see it being generated so I'm going to say "its working" so far.
Now when I want to log out, Long story short I have a logout link that takes them to a page that's supposed to clear all session data and redirect them to the login page. When I'm testing the app and I click the logout link, I get redirected to the login page but when i go back and click the "index page" link. it lets me right in.
In the logout file, trying to FORCE the issue in overkill lol, I have this and nothing seems to work.
unset($_SESSION['usrname']);
unset($_SESSION['usrpass']);
session_unset();
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-3600,'/', '', 0, 0);
header("Location:login-acc.php");
exit;
It redirects me to the login page but again, when I manually go to index page it lets me right in. Or after being redirected to the login page, I hit the "back" button and lets me right in as well.
If I then go into FF Web developer tools app and delete all cookies etc, and navigate to the index page, then it locks me out.
As you can see above ive tried multiple things and in the end, I threw them all together which should do something. My question is since I've put in ALL those functions to try and delete/unset/remove in general the session, what else can I do? I'm a bit lost as to how its supposed to work.
Can someone steer me in the right direction?
You are missing a session_start() at the top of your logout page. It's trying to modify a session that doesn't exist!
You have to start a session in order to end a session. I recommend taking a look at...
http://php.about.com/od/advancedphp/ss/php_sessions_3.htm
// you have to open the session to be able to modify or remove it
session_start();
// to change a variable, just overwrite it
$_SESSION['size']='large';
//you can remove a single variable in the session
unset($_SESSION['shape']);
// or this would remove all the variables in the session, but not the session itself
session_unset();
// this would destroy the session variables
session_destroy();
Whenever I go to a page i.e. login page or any other page, I want to save the name of the page in a $_SESSION variable.
login page:
<?php
session_start();
$_SESSION['page'] = 'login.htm';
?>
It works only for the login page and doesnt overwrite in other pages for e.g. home page:
<?php
session_start();
$_SESSION['page'] = "home.htm";
?>
I need the sesssion variable 'page' to hold the last page I was, can anyone help please?
Why not just use $_SERVER['HTTP_REFERER']? This will give you the previous page in PHP, without having to add anything to sessions.
when you navigate to a new page first retrive the saved "back" variable (and use it in a back link/breadcrumbs or something), and then overwrite the sessions "back" variable with the curent page, to have it ready for the next move =)
If all you need is default "back" functionality you should let the browser handle it.
If what you want is something to be used as a breadcrumb following some internal order (or path in a tree) my advice is to let each page "know" the path that leads to it.
If you really need to know from what page the user came from save it to a previous variable before you write over the current variable.
// Make sure user didnt just refresh the page
if ($_SESSION["current"] !== "currentPage.php") {
$_SESSION["previous"] = $_SESSION["current"];
$_SESSION["current"] = "currentPage.php";
}
You're using different keys.. 'page' and 'back'.
I have a mobile script from detectmobilebrowsers.com that will redirect the user to my mobile site however I also wish that when the URL "http://example.com/?mobile=no" is entered a session will be created that won't redirect the user on every page of my site...
$mobile=$_GET['mobile'];
if(isset($_SESSION['mobile'])){
if($_SESSION['mobile']==="no"){
complete();
}
else{
$_SESSION['mobile']="no";
complete();
}
}
elseif($mobile==="no"){
$_SESSION['mobile']="no";
complete();
}
elseif($_SESSION['mobile']!="no"){
checkMobile();
}
function checkMobile(){
// Mobile Detection Code taken out to save space.
gotoMobile();
}
function gotoMobile(){
echo "<script>window.location='http://m.MySite.org/';</script>";
}
function complete(){
return false;
}
Sorry if I seem confusing but in short terms: Mobile Detection (which is set)... make session mobile=no if user does wishes to view full site and when that session is created it is checked on everypage (same php script) and if I set my session for no mobile I want that to stay on everypage... In my case the only thing that happens is the first page is not redirected but when I go to another page it won't display it unless I add the ?mobile=no but the whole point of the sessions here is so this only needs to be done once.
Before you can begin storing user information in your PHP session, you must first start the session:
session_start();
There must be no markup ouputted before session_start(), not even whitespace! (unless output buffering is used).
See http://php.net/manual/en/function.session-start.php.
It sounds simple, but are you sure you are using session_start() at the top of every page before checking all of your session variables?
I need to destroy a session when user leave from a particular page. I use session_destroy() on the end of the page but its not feasible for me because my page has pagination. My page is: abc.php?page=1 or abc.php?page=2 or abc.php?page=3.
So, I need to destroy a session when a user leaves from abc.php page. How can I do it without using a cookie?
Doing something when the user navigates away from a page is the wrong approach because you don't know if the user will navigate to a whole different page (say contact.php for the sake of the argument) or he/she will just go to the next page of abc.php and, as Borealid pointed out, you can't do it without JS. Instead, you could simply add a check and see if the user comes from abc.php:
First, in your abc.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page:
$_SESSION['previous'] = basename($_SERVER['PHP_SELF']);
Then, add this on all pages, before any output to check if the user is coming from abc.php:
if (isset($_SESSION['previous'])) {
if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) {
session_destroy();
### or alternatively, you can use this for specific variables:
### unset($_SESSION['varname']);
}
}
This way you will destroy the session (or specific variables) only if the user is coming from abc.php and the current page is a different one.
I hope I was able to clearly explain this.
To trigger when the user actually leaves the page, you must use Javascript to send an asynchronous request back to the server. There's no way for the server to magically know the user has "left" a page.
See http://hideit.siteexperts.com/forums/viewConverse.asp?d_id=20684&Sort=0 .
I had a similar issue but mine was on a page reload I wanted variables that I had printed to be destroyed. It was for my login for my web design class I was making error feed back for if user put in a bad username or password. I could get the error to display but if I hit refresh page they errors would just stay there. I found that by just setting the variable to nothing after it printed would kill it. Take a look at what i did:
<p>To access my website please Login:</p>
<form name='login' action="./PHP_html/PHP/login.php" method='post'>
Username: <input type='text' name='username' /><div><?php print $_SESSION['baduser']; $_SESSION['baduser'] = "";?></div><br />
<div style="padding-left: 4px">Password: <input type='password' name='password' /><div><?php print $_SESSION['badpass']; $_SESSION['badpass'] = "";?></div></div>
<input type='submit' value='Login' /> or you can Register
I don't know if this helps at all but it worked for me.
Also, thanks to all you that post on sites like this to help those of us who are still learning.
For a particular page you need to destroy the session, then unset the all session variable
using
unset($_SESSION['varname']);
For the whole site you can use session_destroy();
I solve the problem.First take the current url then chk the page stay on current url.if page is not in the current url then destroy the session.
$url = "http" . ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$page_name="abc.php";
if (!preg_match("/$page_name/",$url))
{
session_destroy();
}
But this code should be used on another pages.Because http is a stateless processes so no way to find when a user leave the page.
You can't tell when a user navigates away from the page, it's simply not possible in any reliable manner.
The best you can do is exploit how cookies work. When starting a session, you're sending a cookie to the client which identifies the client on each subsequent visit, and hence activates the associated session. It is up to the client to send this identification on subsequent visits, and it's up to the client to "forget" his identification.
You can instruct the client to only send the cookie for certain pages, and you can instruct him to forget the cookie when closing the browser (with a lifetime of 0). This can be set using session_set_cookie_params.
Other than that, you can simply ignore the session parameters on pages where they don't matter. You can delete the session (or certain values of it) after some time of inactivity when you assume the client has left.
Borealid deserves credit for pointing to the most elegant solution.
A more kludgey solution is to keep an iframe on the page that is pointed to another "monitor" page which is set to refresh every few seconds. This can be done without JavaScript using:
<meta http-equiv="refresh" content="10">
This refreshes the monitor page every 10 seconds. When this happens, the monitor page can record the time (overwriting the previously recorded time) and session ID on the server somewhere (DB or file).
Then you would have to create a cronjob that checks the file/DB for any sessions that are more than 10~12 seconds old and delete them manually. The session data is usually stored in a directory (specified by your PHP config) in a file named sess_the-session-ID. You could use a PHP function like this:
function delete_session($sessId) {
$sessionPath = session_save_path();
// you'll want to change the directory separator if it's a windows server
$sessFile = "$sessionPath/sess_$sessId";
if (file_exists($sessFile) && unlink($sessFile)) return true;
return false;
}