I'm setting an auth cookie like so:
$identifier = $this->createIdentifier($username);
$key = md5(uniqid(rand(), true));
$timeout = time() + 60 * 60 * 24 * 100;
setcookie('auth', "$identifier:$key", $timeout);
After logout I'm trying to invalidate it by doing this:
setcookie('auth', "", time() - 3600);
When I try to view a restricted page after logging out I'm checking to see if the cookie exists:
if (isset($_COOKIE['auth'])) {
error_log("COOKIE EXISTS: " . print_r($_COOKIE, true));
}
Here is my logout script:
if (!isset($_SESSION)) session_start();
$ref="index.php";
if (isset($_SESSION['username'])) {
unset($_SESSION['username']);
session_unset();
session_destroy();
// remove the auth cookie
setcookie('auth', "", time() - 3600);
}
header("Location: " . $ref);
exit();
I shouldn't be hitting this code but I am. After logging out I see the cookie has been removed from my browser. Any idea how it's finding it again after logging out?
UPDATE
This code get called from another class that checks user privs etc. The only files it doesn't work with are files that reference it from one directory above. For instance
Any file referencing it like this works OK:
<?php include_once('classes/check.class.php');
Any file referencing it like so DO NOT work:
<?php include_once('../classes/check.class.php');
Any thoughts what might be causing this?
After you log the user out you need to do a redirect to cause a new page load. Since cookies are sent with page requests until a new requests is made those cookies are still alive even after you "delete" them.
Related
I have done a memberpage using an external interface to check if the user is allowed to login to the memberpage. The code looks like this
<?php
require (__DIR__ .'/Permission/checkUser.php');
if (isset($_POST['submit'])){
session_start();
$errors = array();
if (empty ($_POST ['user']) ||
empty ($_POST ['password'])) {
$errors[] = 'Användarnamn och passord får inte vara tomt';
}
$checkuser = new checkUser();
if ($checkuser->checkUser($_POST ['user'], $_POST ['password']) == false){
$errors[] = 'Kontrollera user och lösenord';
}
if (count($errors) == 0) {
$_SESSION['userid'] = md5(microtime());
$_SESSION['start'] = time();
wp_redirect( get_permalink( 18341 ) );
die;
}
}
?>
If a succesful result from the SOAP call is returned the user are redirected to memberpage. The code fore memberpage are as following
<?php
require_once 'sessioncheck.php';
get_header();
$container = get_theme_mod( 'understrap_container_type' );
?>
After performing the check the HTML are presenting the memberpage content.
The sessioncheck.php has the following code:
<?php
session_start();
if (!isset($_SESSION['userid'])){
//session does not exist send back to loginpage
header('Location: memberLogin');
}
if (isset($_SESSION['start']) && (time() - $_SESSION['start'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header('Location: memberLogin');
}
?>
It is suppose to unset and destroy the session if 30 minutes has passed.
My problem is that sometimes, often after a session has expired the redirect in the first code does not work. Its actually not even trying to load the memberpage. I first thought I had some problems with the session variables but now I think there might be some garbage from the session that causes this problem. It semse to be intermittent but I have asked other to test the page (using the right cred) and they always semse to be able to login on there first attempt to fail later on.
What am I doing wrong? Using PHP 7.4 with the latest WP core.
EDIT:
Added the following code to clean up sessions and cookie
$_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"]
);
}
// Finally, destroy the session.
session_destroy();
Now everything works fine when I am logged in as an adminuser in wordpress. However, as soon as I log out it stops working. However, the session is saved and if I log in again at WP, then I am able to enter the memberpage without doing the login procedure. I updated the page in WP (memberpage) and it worked again. This is all confusing me right now... :(
Solved, clearing Session cookie and purged cache solved the issue. Needed exclude memberpage from cache. Didnt work with LiteSpeed cache
I have a simple website where you need only a password to access the contents. Then there are 3 fields where user inputs data, which are then stored in cookies. In the end - there is a logout script that resets the session and unsets cookies.
Please find the relevant code below:
Login page (index)
<?php
session_start();
$password = '';
$wrongPassword = '';
if (isset($_POST['sub'])) {
$password = $_POST['login_passcode'];
if ($password === 'PASSCODE') {
$_SESSION['login'] = true;
header('LOCATION:/personal.php');
die();
} else {
$wrongPassword = true;
}
}
if (isset($_COOKIE['m_username'])) {
header('LOCATION:/personal.php');
die();
}
?>
The page with contents, where user inputs name, department and start date
<?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header("Location:/index.php");
die();
}
?>
and the logout script:
<?PHP
session_start();
if (isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_username'])):
setcookie('marriott_username', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_startdate'])):
setcookie('marriott_startdate', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_department'])):
setcookie('m_department', '', time() - 7000000,'/');
endif;
$_SESSION = array();
session_destroy();
header ("Location:/index.php");
die();
?>
jQuery to create cookies below:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Cookies do expire (at least on chrome), however after trying to access website after a few hours or days, I get the error about too many redirections. I believe this might be due to some differences between session expiration time and cookies expiration time (5 days for cookies), but I don't really know where to start fixing these...
Also, on Internet Explorer (IE8) the redirects problem occurs even when I go through logout directly.
Will be grateful for any help,
E.
You are correct in thinking different cookie expirations are behind the too many redirects problem.
If isset($_COOKIE['m_username']) is true in the index page, then you are redirected to the personal page, in which if if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) is also true, it sends you back to the index, therefore creating a loop. This would be caused by the session cookie expiring before the cookies you set.
The $_COOKIE and $_SESSION superglobals refer to two different sets of cookies. One solution is to use just the PHP session and store all your session data in the $_SESSION superglobal.
For example:
$_SESSION['m_username'] = 'whatever_value';
This will however generate an overhead in extra memory usage. If you still want to use your own cookies then just make sure any logic determining redirects is based on the session, not the presence of cookies you set.
For example:
// When logging in
$_SESSION['logged_in'] = true;
// On every page that requires login
if(!$_SESSION['logged_in']) // Redirect
In my PHP project, I want to add a user remember me checkbox so that everybody can choose to stay logged in:
Until now I do my normal log in like:
public function loginUser($psMail, $psPwd, $pnRememberMe = 0) {
// Check credentials and so on
// If mail and password matches
if(CREDENTIALS OKAY) {
$_SESSION["username"] = "foo";
$lnExpire = time() + 3600 * 24 * 60;
setcookie("remember", base64_encode(USERID), $lnExpire);
setcookie("rememberToken", md5(SOMESTUFF), $lnExpire);
}
}
When I log in, I can see the created cookie variables with:
print_r($_COOKIE);
Now I try to leave the site with my logout function:
// Unset the session variables
$_SESSION = array();
// Destroy the session.
session_destroy();
But now, when I am at the landing page, there are also my cookies gone?
Could this be because of my session site settings?
ini_set("session.use_only_cookies", "1");
ini_set("session.use_trans_sid", "0");
php function setcookie has fourth argument path, from documentation "The path on the server in which the cookie will be available on". By default it set path to actual your directory. Try set "/" Then it will be available for all domain. http://php.net/manual/en/function.setcookie.php
Try this code hope it will work for you
if(count($_POST>0) && isset($_POST['checkbox']))
{
setcookie('name',$_POST['uname'],time()+3600);
setcookie('password',$_POST['pw'],time()+3600);
}
elseif(count($_POST)>0)
{
setcookie('name','',time()-3600);
setcookie('password','',time()-3600);
}
if(count($_POST)>0 && $_POST['uname']!="" && $_POST['password']!="")
{
if(isset($_COOKIE['name']) && isset($_COOKIE['password']))
{
echo $_COOKIE['name'];
echo $_COOKIE['password'];
}
your login detail code here.....
I've got a problem, user can't Log Out because the $_COOKIE's are not actually deleting. I can't find out what could be the problem.
This code is used only once at Log In:
// Log In
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('user_id', $row['user_id'], time() + 2592000);
setcookie('username', $row['username'], time() + 2592000);
The code below is checking if cookies are set up to make users to be logged in when they relaunch their browser (the "keep me logged in" effect).
// Starting Session
session_start();
// If the session vars aren't set, try to set them with cookies
if (!isset($_SESSION['user_id'])) {
// This check always equals true because cookies are not deleting on Log Out
if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['username'] = $_COOKIE['username'];
}
}
This code is launched only once on Log Out:
// Log Out
session_start();
if (isset($_SESSION['user_id'])) {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 2592000, '/');
}
session_destroy();
}
setcookie('user_id', '', time() - 2592000);
setcookie('username', '', time() - 2592000);
Don't use relative times for cookies. if you want to expire a cookie, then use Jan 1 1970 00:00:00. You're assuming that the user's clock is accurate and within an hour of your server's. Given how many people have their VCRs blinking 12:00, this is a bad assumptiong.
As well, why are you storing login information in a client-side cookie? The only cookie you should really be setting is the session cookie, which session_start() already does for you, then store all that information in $_SESSION only.
I think you're doing it way too complicated.
My example where it's just an admin login:
login.php
#session_start();
if (isset($_GET['login'])) {
if($_GET['name'] == $s['admin']){
if($_GET['pw'] == $s['adminpw']){
$_SESSION['isadmin'] = true;
}
}
}
logout.php
#session_start();
unset ($_SESSION['isadmin']);
use session_set_cookie_params() to set the lifetimes
I found why cookies were not removing!
To make sure your cookies will remove, set the same path on removing cookies as on setting them.
// Setting Cookie
setcookie(session_name(), '', time()-2592000, '/'); // The path here is "/"
// Removing Cookie
setcookie(session_name(), '', time()+2592000, '/'); // The path here is "/"
I have a login/logout system and need the cookies to work across www.mydomain.com as well as mydomain.com. The problem I'm having is on deleting the cookies. On the login I am setting the cookies like this:
session_start();
//set session vars
setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30), '/', 'domain.com');
setcookie('full_name', $row['first_name']." ".$row['last_name'], time() + (60 * 60 * 24 * 30), '/', 'domain.com');
Which works, and the cookies are saved and it works with or without the www. It allows the profile page to be viewed which has this code:
session_start();
if(!isset($_SESSION['user_id'])) {
if(isset($_COOKIE['user_id']) && isset($_COOKIE['full_name'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['full_name'] = $_COOKIE['full_name'];
}
}
if(!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
The problem is logging out:
session_start();
if(isset($_SESSION['user_id'])) {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/', 'domain.com');
}
session_destroy();
}
setcookie('user_id', '', time() - 3600, '/', 'domain.com');
setcookie('full_name', '', time() - 3600, '/', 'domain.com');
The cookies are deleted but only for the current domain. So if I login from domain.com/login.php and logout from domain.com/logout.php, domain.com/profile.php doesnt work (good) but I will still be able to view www.domain.com/profile.php if I have visited the www. version before logging out. And vice versa I can logout from www.domain.com/logout.php and still be able to view domain.com/profile.php. Is there a way to delete all cookies across the subdomains?
Use '.domain.com' instead 'domain.com' to work with all subdomains.
The OP wrote in a comment:
Finally figured it out, the session was creating a separate cookie when the subdomain was changed. So logging out would delete one session cookie but leave the other. The solution was to name the session before starting it so it always has the same name:
$some_name = session_name("cool_session");
session_set_cookie_params(0, '/', '.domain.com'); session_start();