I have a PHP script which returns a receipt to a customer purchasing on my website. When they get the receipt, I want to be able to start a new session. So far I have a piece of code at the end of the script which returns the receipt page. It is:
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(),
'',
time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
session_destroy();
session_regenerate_id(true);
When I use the website and go through the purchasing process, after the receipt page is served, the session id remains the same.
Yet, I took the above code and placed it in a seperate script called 'regenerate.php'. I then called this in another script, like so:
<?php
include("regenerate.php");
session_start();
echo("<br>id:".session_id());
include("regenerate.php");
session_start();
echo("<br>id:".session_id());
include("regenerate.php");
session_start();
echo("<br>id:".session_id());
include("regenerate.php");
session_start();
echo("<br>id:".session_id());
?>
When I run this script, then session id changes each time the regenerate script is run. However, the same code does not work in the intended page I am trying to serve up before restarting the session.
Is there any reason it might work in one case and not the other? I thought it might be because text is already being written out to output, however it happens in both cases.
You can't generate a new session during the same request, after sending output to the browser.
Simply because the session cookie has already been sent - with the headers. So most likely your second call to session_start() gives an error.
You can find more about turning display_errors On here: How do I get PHP Errors to display?
Related
I want a method to force logout all logged in users using Php
the session check code goes like this:
<?php
include "dbConn.php";
session_start();
if (!isset($_SESSION['login_user'])) {
header("location:Login.php");
die();
}
?>
so it depends on the session variable "$_SESSION['login_user']" , So is there a way to unset this variable for all the logged in users ?
Regards
As noted in my comment, you could also just change the session key that you are testing. I would recommend making that globally available and assign it a version number that you increment when you want to log everyone out.
Here's a full version that also includes full destruction of the session's data that you may or may not want. This code hasn't been tested but I'm fairly confident it is mostly accurate.
Also, this doesn't "log everyone out", it instead logs everyone out the next time they access the site. For most people this is the same thing, but it is possible that some site's might have a need for the former, and I think the other comments address that instead.
// This should be in a globally available file, and all
// session checks should rely on this
const SESSION_USER_KEY = 'login_user_v1';
session_start();
if (!isset($_SESSION[SESSION_USER_KEY])) {
// Only needed if you potentially have additional code before the redirect
$_SESSION = [];
// Optionally kill the cookie, see https://www.php.net/manual/en/function.session-destroy.php#example-4744
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
session_destroy()
header("location:Login.php");
die();
}
So, I have the following logout script (as taken from php.net):
<?php
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
header(...); //See Below
?>
The website has a header that echos either a login form (when not logged in) or "Welcome, User" (when logged in).
I have tried:
header("location:http://example.com");
in my logout script but the website header echos "Welcome, User" still until the page is refreshed. It is seemingly loading from cache(?).
One way I have gotten around this is changing the line to:
header("location:http://example.com?a=".uniqid());
As much as this works, it looks ugly in the address bar.
Is there a way to achieve the redirect without loading from cache or changing the address bar to remove the GET variable?
EDIT: OK, so this is strange... When I have the Chrome Dev Tools open to check the header response, it works fine. As soon as I close the Dev Tools, the problem comes back. Really need some help with this people!
I am having an issue with the session variables.
I am having a simple signup php page that uses ajax calls to verify username and email address if they already exist. It also has an ajax image uploader that gives a preview of the selected image.
Now this is how I am setting the session variable :-
session_start();
session_unset();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
session_start();
$_SESSION['avurl'] = $filename;
$filename is valid as it is echoed in the above code just after this snippet.
In the page where I need to use this session variable I have this :-
session_start();
$av_url = $_SESSION['avurl'];
Now the weird thing is that whenever this runs the first time the session variable doesn't have any value. But the second time it works.
How I came to check this is that I created a test.php which just echos $_SESSION['avurl'] and the first time it never shows anything but the second time it does.
What I figured out from this is that once it echoes this session variable it starts working to store the value.
And all that code that I am using to set that variable is edited from just :-
session_start();
$_SESSION['avurl'] = $filename;
to that as this also didn't work and I thought that this could be a problem with already existing sessions.
Thankyou
Hope this is enough information for solving my problem !!
session_start();
session_unset();
This code delete Your session... Why You doing this?
I am working on a PHP project where in I need to clear the seesion on click browser close.
My project :
Index.php -> userdata.php -> reports.php ->finalreport.html
is it possible to handle session destroy?
I need to clear session , whenever user exits browser while they are in any page.
Please let me know how can we handle this.
the session is destroyed when the user closes the browser**. if you want to destroy it as soon as the user unloads the page, you could add a handler to the page unload event (something like jquery unload) and do a ajax request to a script that just clears the session.
EDIT: per OP's request, i'll add specific code.
1) in all pages (Index.php, userdata.php, reports.php, finalreport.html) add this javascript code
$(window).unload(function() {
$.get('session_destroyer.php');
});
2) in session_destroyer.php use this code (taken from php.net)
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// 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();
?>
hope this helps
** NOTE: as one commenter noted, this assumes you're using cookie-based sessions (which is the default in PHP, i think)
I'm trying to correctly log out of an admin user. Here is my function:
function logout()
{
$_SESSION = array(); //destroy all of the session variables
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
}
Basically, once I authenticate the password, I set the session as being valid (only 1 user total). Now, when the admin hits logout, I want to destroy the current session, and also destroy the cookie, so that they can't just go back to the admin page using the stored session cookie in the browser. but my code doesn't work. i hit logout, and i can just directly navigate back to the admin page. however, if i delete my cookies, the functionality is perfect. so what's wrong with the cookie deleting function here?
If you really want to cover all bases try doing:
setcookie (session_id(), "", time() - 3600);
session_destroy();
session_write_close();
That should prevent further access to the session data for the rest of PHP execution. The browser may still show the cookie being set however the $_SESSION super will be blank
Maybe your problem is not the cookie, but the browser showing a cached version of your admin page. Could that be? If it disappears when you hit F5, it's probably that. This can be sorted by setting the right cache-control headers.
Check out this SO question on the issue of how to set caching. The question is about exactly the other way round (forcing browsers to cache) but you'll figure out what to change to turn caching off.
Just a tip for others who are having issues expiring session cookies:
PHP - why can't I get rid of this session id cookie?
Always use session_get_cookie_params() as in the answer to the question in the link above.