Here is my login cookies being set
setcookie('username[0]',$username,time()+(60*60*24*365));
setcookie('username[1]',$userid,time()+(60*60*24*365));
setcookie('username[2]',$subscribed,time()+(60*60*24*365));
setcookie('password',md5($password),time()+(60*60*24*365));
setcookie('admin',$admin,time()+(60*60*24*365));
Here is my logout function
function logout($return) {
setcookie('username[0]', '', time()-(60*60*24*365));
setcookie('username[1]', '', time()-(60*60*24*365));
setcookie('username[2]', '', time()-(60*60*24*365));
setcookie('password', '', time()-(60*60*24*365));
setcookie('admin', '', time()-(60*60*24*365));
header( 'Location: ' . $return );
echo "<div class='fontall'><span class='fontdif'>You've been logged out. </span><a href='$return'>Click Here</a><span class='fontdif' to return</span></div>";
}
When i try to log out and return to the page i am still logged in? What did i do wrong?
If you got the 'cannot modify headers' error, it means you echo out something before setcookie. setcookie must do before any content echo out.
Like other headers, cookies must be sent before any output from your
script (this is a protocol restriction). This requires that you place
calls to this function prior to any output, including and
tags as well as any whitespace.
// 1. Find the session
session_start();
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
That should work.
Probably..u didn't destroy the session?
Nothing seems to be wrong with the code - they should be deleting the cookies. Are you sure that the cookies are not deleting? After you logout, try checking if the cookies exist. You may do so using the browser that show the active cookies. Or alternatively you may try reading the cookies using PHP.
Second, how are you checking if the session is still valid? Can you please share that piece of code? And where do you check your session - do you do them on all pages?
Related
Hy I am new to php and trying to destroy a session according to the php documentation here: http://php.net/manual/en/function.session-destroy.php
so I am using this code:
<?php
session_start();
echo 'cokkies before delete session';
var_dump($_COOKIE);
var_dump($_SESSION);
echo '-------------- <br>';
$_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();
echo 'cokkies after delete session';
var_dump($_COOKIE);
var_dump($_SESSION);
?>
what I dont understand is, doesnt matter how many times I run this code the PHPSESSID property in the $_COOKIE superglobal is always exactly the same.
So is then the session id on the server destroyed at all and just the id in the cookie stays alive? And overall why does it work out like this.
Thanks for the answers
Hy So I have found out why the setcookie() function didnt destroy the PHPSESSID cookie. the session_set_cookie_params() function needs to be set before starting the session and so later the setcookie() function will be able to expire the the PHPSESSID cookie.
this code works:
<?php
$lifetIme = 60 * 60 * 24 * 360;
$path = '/';
$domain = 'yourdomain';
$secure = isset($_SERVER["HTTPS"]);
$httponly = true;
session_set_cookie_params ($lifetIme, $path, $domain, $secure, $httponly);
session_start();
$expire = strtotime('-1 year');
setcookie('PHPSESSID', '', $expire, $path, $domain, $secure, $httponly);
session_destroy();
?>
it will create and then destroy the session completely and the next call to the server from the same browser wont know about the the prev session and its PHPSESSID cookie
Just use session_regenerate_id() after destroying the session.
https://secure.php.net/manual/en/function.session-regenerate-id.php
Also destroying a sessions doesn't unset a cookie.
ok hi, just wanna leave a few things out. Ok it’s simple, session destroyed doesn’t unset whats been set on cookie. Like we all know, cookies are available until the validity elapses. And even if the session get regenerated it would still update the cookie. I’ll suggest you have it controlled else if you refresh that page a million times you would still have the same result sent as an output. It’s more like doing the same thing and expecting a better result. I could write you a snippet if you want. Hope this helps
=== My discovery ==
<?php
session_start();
define('NEWLINE', '<br><br>');
echo "cookie before delete session. <br>";
var_dump($_COOKIE);
echo NEWLINE;
echo "session Here <br>";
var_dump($_SESSION);
echo NEWLINE;
echo "------------------------<br>";
$_SESSION = array();
if (ini_get('session.use_cookies'))
{
$params = session_get_cookie_params();
echo "cookie already has PHPSESSID even before you set it here ..<br>";
// The solution i could arrive with
// without this PHPSESSID wouldn't give you a new id.
session_regenerate_id();
}
// now destroy
session_destroy();
echo "Cookie here would not change. Just refresh the page and try commenting session_regenerate_id() to see the difference. <br>";
var_dump($_COOKIE);
echo "Session when destroyed. <br>";
var_dump($_SESSION);
?>
See the documentation:
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.
… even if it did unset the session cookie, the $_COOKIES superglobal includes all the cookies that the browser sent when it made the request. It would require time travel for session_destroy to prevent the browser from sending them in the request that is currently being processed.
what I dont understand is, doesnt matter how many times I run this code the PHPSESSID property in the $_COOKIE superglobal is always exactly the same.
If you the session ID sent by the browser doesn't match an existing session, when you call start_session, then it still uses the same session ID for the new session.
session_regenerate_id forces the generation of a new id, start_session does not.
I am trying to make a platform with a login system and I am storing the username and the password in cookies to make the user stay logged in even if it closes the browser and then enters again. I managed to save the cookies but I don't know how to make the logout button.
Here is the code:
function logout() {
$('body').append("<?php setcookie('username', null); setcookie('password', null); unset $_COOKIE['username']; unset $_COOKIE['password']; ?>");
location.assign("index.php");
}
You are trying to include PHP code in JavaScript, which will not work like that.
You could either delete the cookie with jQuery as suggested here:
function logout() {
$.cookie("username", null, { path: '/' });
location.assign("index.php");
}
or by calling a PHP file with the following PHP code:
setcookie("username", "", time() - 3600, '/');
Try:
setcookie('username', null, -1, '/');
setcookie('password', null, -1, '/');
You are trying to execute server code inside client code.
That won't work. It'll literally append what's inside the append method.
You need to write a logout.php file and inside it have your server side logic.
Such as
<?php
session_destroy();
setcookie("cookie", "value", 1);
header("Location: index.php");
?>
Set cookie to 1second after epoch instead of 0 so that the cookie expires right away and not at the end of the browser session.
Also note that you shouldn't store the password in the cookie. Rather store the session key in the cookie using session_start();
i have this file
secure.php
session_start();
if(empty($_SESSION['u_name'])) {
header("Location:emprego.php");
}
if(isset($_GET['logout'])) {
session_destroy();
header("Location:emprego.php");
}
$name = $_SESSION['u_name'];
?>
<li><?php echo "<a href='emprego.php?logout' id='D'>Logout</a>";?></li>
basically, if i do logout, i will be redirected to emprego.php. But if i click in back page button (arrow in browser), i can view the same page (secure.php).
my question is, why?
thanks
http://nl2.php.net/manual/en/function.session-destroy.php
Take a look at example 1 here. It clearly states that you have to clear $_SESSION as well.
if(isset($_GET['logout'])) {
unset($_SESSION['u_name']); //makes it non-existent (it does unset) that variable
session_destroy();
header("Location:emprego.php");
}
Your browser keeps a copy of the page in cache. When you click the back button, you are seeing the local cached copy, not the current page from the server. If your security is set up properly, you will not be able to do anything meaningful from that cached page.
It is for this reason that secure websites (bank sites, for example) tell you to log off and clear your cache (or close the browser) after you log out.
If you're using session cookies, also try expiring the session cookie explicitly, like this:
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
Also, going back in the browser only loads a cached copy of the page. If you tried interacting with the cached page to fetch a new page from the server, you shouldn't be able to proceed.
I recently found header_remove(); http://php.net/manual/en/function.header-remove.php
Caution: This function will remove all headers set by PHP, including cookies, session and the X-Powered-By headers.
Not sure whether this is the appropriate way to do it, but it's pretty effective for log out functionality.
All the other solutions didn't seem to work for me. However, this workaround did the trick. Basically, the code below keeps calling the logout until the logout finally succeeds:
if (isset($_GET["logout"])){
if (isset($_SESSION["username"])) {
unset($_SESSION["username"]);
session_destroy();
header("Location:/?logout=true");
exit;
}
header("Location:/");
exit;
}
HEY GUYS
deleting cookie is a easy thing to do in php but problem is untill i get out of my browser it still exists
setcookie("PHPSESSID", false);
setcookie("PHPSESSID","",time()-31536000);
any way to delete this cookie whithout need of closing the browser ?!
so what do u think ?!
Cookie headers are only sent as soon as the user laods a new page. So just unsetting the browser server side will not delete it on the client.
Also be aware of the domain. You should always use a fourth parameter to set a cookie for all paths on your site. If you don't do that, a cookie from a subfolder might still exists.
You can check with cookies are set using some JavaScript function or the Web Developer Toolbar for Firefox.
Properly destroy the session and set the session cookie var to expire in the past.
From the PHP.net manual on session destroy:
<?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();
?>
When using session_write_close() in a shutdown function at the end of my script - PHP just dies. There is no error logged, response headers (firebug), or data (even whitespace!) returned. I have full PHP error reporting on with STRICT enabled and PHP 5.2.1.
My guess is that since session_write_close() is being called after shutdown - some fatal error is being encountered that crashes PHP before it has a chance to send the output or log anything.
This only happens on the logout page where I first:
...
//If there is no session to delete (not started)
if ( ! session_id())
{
return;
}
// Get the session name
$name = session_name();
// Delete the session cookie (if exists)
if ( ! empty($_COOKIE[$name]))
{
//Get the current cookie config
$params = session_get_cookie_params();
// Delete the cookie from globals
unset($_COOKIE[$name], $_SESSION);
//Delete the cookie on the user_agent
setcookie($name, '', time()-43200, $params['path'], $params['domain'], $params['secure']);
}
// Destroy the session
session_destroy();
...
then 2) do some more stuff 3) issue a redirect and 4) finally, after the whole page is done the register_shutdown_function(); I placed earlier runs and calls session_write_close() which saves the session to the database. The end.
Since this blank response only occurs on logout I'm guessing that I'm not restarting the session properly which is causing session_write_close() to die fatally at the end of the script.
Weird. The problem seems to be the fact that I am destroying the session before I remove the cookie.
This works:
// Delete the session cookie (if exists)
if ( ! empty($_COOKIE[$name]))
{
//Get the current cookie config
$params = session_get_cookie_params();
// Delete the cookie from globals
unset($_COOKIE[$name], $_SESSION);
//Delete the cookie on the user_agent
setcookie($name, '', time()-43200, $params['path'], $params['domain'], $params['secure']);
}
// Destroy the session -----------------------------------------
session_destroy();
while this kills the page:
// Destroy the session -----------------------------------------
session_destroy();
// Delete the session cookie (if exists)
if ( ! empty($_COOKIE[$name]))
{
//Get the current cookie config
$params = session_get_cookie_params();
// Delete the cookie from globals
unset($_COOKIE[$name], $_SESSION);
//Delete the cookie on the user_agent
setcookie($name, '', time()-43200, $params['path'], $params['domain'], $params['secure']);
}
Does anyone know why?