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.....
Related
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
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.
I am trying to detect if a user on my page has cookies enabled or not. The following code performs the check, but, I have no idea on how to redirect the user to the page they came from.
The script starts a session and checks if it has already checked for cookies. If not, it redirects the user to a test page, and since I had called session_start() in the first page, I should see the PHPSESSID cookie if the user agent has cookies enabled.
The problem is, ths script might be called from any page of my site, and I will have to redirect them back to their selected page, say index.php?page=news&postid=4.
session_start();
// Check if client accepts cookies //
if (!isset($_SESSION['cookies_ok'])) {
if (isset($_GET['cookie_test'])) {
if (!isset($_COOKIE['PHPSESSID'])) {
die('Cookies are disabled');
} else {
$_SESSION['cookies_ok'] = true;
header(-------- - ? ? ? ? ? -------- -);
exit();
}
}
if (!isset($_COOKIE['PHPSESSID'])) {
header('Location: index.php?cookie_test=1');
exit();
}
}
I think its better to make one file set cookie and redirect to another file. Then the next file can check the value and determine if cookie is enabled. See the example.
Create two files, cookiechecker.php and stat.php
// cookiechecker.php
// save the referrer in session. if cookie works we can get back to it later.
session_start();
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// setting cookie to test
setcookie('foo', 'bar', time()+3600);
header("location: stat.php");
and
stat.php
<?php if(isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar'):
// cookie is working
session_start();
// get back to our old page
header("location: {$_SESSION['page']}");
else: // show the message ?>
cookie is not working
<? endif; ?>
Load cookiechecker.php in browser it'll tell cookie is working. Call it with command line like curl. It'll say, cookie is not working
Update
Here is a single file solution.
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
HTTP_REFERER did not work for me, seems like REQUEST_URI is what I need.
Here is the code I finally used:
session_start();
// ------------------------------- //
// Check if client accepts cookies //
// ------------------------------- //
if( !isset( $_SESSION['cookies_ok'] ) ) {
if( isset( $_GET['cookie_test'] ) ) {
if( !isset( $_COOKIE['PHPSESSID'] ) ) {
die('Cookies are disabled');
}
else {
$_SESSION['cookies_ok'] = true;
$go_to = $_SESSION['cookie_test_caller'];
unset( $_SESSION['cookie_test_caller'] );
header("Location: $go_to");
exit();
}
}
if( !isset( $_COOKIE['PHPSESSID'] ) ){
$_SESSION['cookie_test_caller'] = $_SERVER['REQUEST_URI'];
header('Location: index.php?cookie_test=1');
exit();
}
}
// ------------------------------- //
There's no need to save the original URL and redirect to it afterwards. You can perform a transparent redirect via AJAX which doesn't trigger a page reload. It's very simple to implement. You can check my post here: https://stackoverflow.com/a/18832817/2784322
I think this is easiest solution. Doesn't require separate files and allows you to proceed with script if cookies are enabled:
$cookiesEnabled = true;
if (!isset($_COOKIE['mycookie'])) {
$cookiesEnabled = false;
if (!isset($_GET['cookie_test'])) {
setcookie('mycookie', 1, 0, '/');
#ob_end_clean();
$_SESSION['original_url'] = $_SERVER['REQUEST_URI'];
$uri = $_SERVER['REQUEST_URI'];
$uri = explode('?', $uri);
$q = (isset($uri[1]) && $uri[1])?explode('&', $uri[1]):array();
$q[] = 'cookie_test=1';
$uri[1] = implode('&', $q);
$uri = implode('?', $uri);
header('Location: '.$uri);
die;
}
} else if (isset($_GET['cookie_test'])) {
#ob_end_clean();
$uri = $_SESSION['original_url'];
unset($_SESSION['original_url']);
header('Location: '.$uri);
die;
}
// if (!$cookiesEnabled) ... do what you want if cookies are disabled
PROBLEM
I've got an admin panel. Currently only Mozilla is able to process log ins. Browsers like Chrome, IE, Opera won't even show any message carried through sessions thus no one is able to log in any browser but Mozilla.
SOME INFORMATION
I'm using PHP 5.3.6 on my server, PHP 5.3.5 on my local
computer.
My code is Object Oriented.
ini_set("session.use_only_cookies", 1); and
ini_set('session.cookie_secure', 1); are used in construction method
of my session class.
This website on SLL
Login process: First I gather all information from form, validate and gather data. After validation if everything is right, I send this data to login method in my session class.
public function login ($user) {
global $siteSettings;
if ($user) {
$this->id = $_SESSION['id'] = $user->id;
$this->username = $_SESSION['username'] = $user->username;
$this->fullName = $_SESSION['fullName'] = $user->fullName;
$this->group_id = $_SESSION['group_id'] = $user->group_id;
$this->groupName = $_SESSION['groupName'] = $user->groupName;
$this->lastLogin = $_SESSION['lastLogin'] = $user->lastLogin;
$this->isAdmin = $_SESSION['isAdmin'] = ($user->admin == 1) ? true : false;
$this->isAgent = $_SESSION['isAgent'] = ($user->agent == 1) ? true : false;
self::$language = $_SESSION['language'] = ($user->language != "" || $user->language != NULL) ? $user->language : self::$language;
if ($user->language != "" || $user->language != NULL) {
$_SESSION['language'] = $user->language;
}else {
if (!defined(DEFAULT_LANGUAGE)) {
$browserLang = "|".$_SERVER["HTTP_ACCEPT_LANGUAGE"];
$browserLang = getStringBetween($browserLang, "|","-", FALSE);
if (!file_exists(LANGUAGES.$browserLang.".php")) $browserLang = FALSE;
}
$_SESSION['language'] = ($browserLang) ? $browserLang : DEFAULT_LANGUAGE;
}
# When 2 Update session_id
$date = new DateTime("now");
$UpdateTime = $siteSettings->session->timeOut * 60;
$date->add(new DateInterval("PT".$UpdateTime."S"));
$_SESSION['SIDUpdateTime'] = $date->format("Y-m-d G:i:s");
# UPDATE LAST LOGIN & ADD SESSION ID
# Clear Fields
members::clearFields();
members::$fields['id'] = $_SESSION['id'];
members::$fields['lastLogin'] = date("Y.m.d G:i:s");
members::$fields['lastLoginIP'] = $_SERVER['REMOTE_ADDR'];
# GET THE SALT
$saltInfo = members::getData("id", "salt", members::$fields['id']);
# SETTING SESSION ID ENCRYPTION
crypt::setKey($saltInfo->salt);
members::$fields['sessionID'] = crypt::encode(session_id());
members::$fields['sessionIP'] = $_SERVER['REMOTE_ADDR'];
members::$fields['sessionAgent'] = $_SERVER['HTTP_USER_AGENT'];
members::save();
$this->loggedIn = true;
var_dump($_SESSION);
}
}
When I dumb the data I can see $_SESSION got some values.
Just to test it, I stopped the script where after var_dump($_SESSION); (added die();) I created test.php file and tried this;
<?php
ob_start();
session_start();
echo '<pre>';
var_dump($_SESSION);
echo '<pre>';
ob_end_flush();
?>
Output is array(0) {}
But when I try exactly the same thing with Mozilla, output of test.php is the way it should be (matching with login method's result in my session class).
I have tried from my local computer and I don't experience the same
problem.
I disabled all java script and jquery codes from the page just to
have no 'maybe' in my mind.
After dumping the data, script is stopped. That's why $_SESSION variable shouldn't change. For some reason when it is on the server only Mozilla is able to show expected result while other browsers shows NULL.
At this point I really don't know what to think of about this problem to try to solve it. All I can think of is, this problem is possibly related to server configuration. But then, PHP is server side programming. PHP shouldn't display different behavior for browsers like Jquery, CSS, HTML...
I'm sorry, I can't provide admin panel link. Considering this is an active admin panel. If necessary I could install it on another domain to let you try but I believe the information I gave above explains everything.
Thank you for your help in advance.
I had a similar problem... just enable the cookies.. so that after login the code to set the sessions will be executed and the sessions will be set. may be the sessions r not able to set...
also check this http://php.net/manual/en/function.session-cache-limiter.php
If something large doesn't work, trim it down, test & debug, and build up from there.
Does this work? (Run it twice).
<?php
session_start();
echo "Session ID: " . session_id() . "<br/>\n";
if (!isset($_SESSION['test']))
{
$_SESSION['test'] = "foobar";
echo "Setting session variable: ";
echo $_SESSION['test'];
}
else
{
echo "Restoring session variable: ";
echo $_SESSION['test'];
}
If this works in all browsers, it's got something to do with your code. An empty session might have something to do with a cookie that can't be written, for example. Also set error reporting to E_ALL | E_STRICT, so you'll see everything that goes wrong.
It turns out Mozilla FireFox is able to process some data but other browsers I tried with are not and therefore they reset the whole session with each page load.
I had no problem with my local computer but on the server I had sessions problem. I don't know why session_set_cookie_params(); and setcookie(); didn't work on the server so I had to code longer version;
private static function sessionLifeTime() {
global $siteSettings;
# HOW LONG WE WANT SESSIONS
$lifeTime = intval($siteSettings->session->timeOut) * 60;
if (isset($_SESSION['id']) && isset($_SESSION['lastActivity']) && (time() - $_SESSION['lastActivity'] > $lifeTime) ) {
// SEND INFORMATION TO USER
self::logout();
}
$_SESSION['lastActivity'] = time();
}
Replacing my method with the code above solved the problem.
Thank you all for your time, concern and interest.
I'm validating a login form with jQuery AJAX call to PHP. In php, I create a session and if they checked the 'remember me' checkbox, I want to create a cookie. Here's the php code:
<?php
include '../includes/connection.php';
date_default_timezone_set('GMT');
$name = $_POST['username'];
$pass = $_POST['password'];
$query = mysql_query("SELECT id, username, password FROM users WHERE username = '$name' LIMIT 1");
if(mysql_num_rows($query) == 0) {
echo 'error';
exit;
}
while($row = mysql_fetch_array($query)) {
if($row['username'] == $name && $row['password'] == $pass) {
session_start();
$_SESSION['username'] = $row['username'];
$_SESSION['usrID'] = $row['id'];
echo 'success';
if($_POST['remember']) {
setcookie('username', $row['username'], $exp);
setcookie('password', $row['password'], $exp);
setcookie('usrID', $row['id'], $exp);
}
} else {
echo 'error';
exit;
}
}
?>
The session is set successfully, however the cookie is not set at all. I've tried setting all the values (domain, path, etc.) but that didn't change anything. Is there anything obvious I'm missing?
Here are few suggestions:
Make sure that you are specifying the correct expiration format of date
When setting a cookie on a page that redirects, the cookie must be set after the call to header('Location: ....'); eg:
header('Location: http://www.example.com/');
setcookie('asite', $site, time()+60*60, '/', 'site.com');
If you have human urls like www.domain.com/path1/path2/, then you must set cookie path to / to work for all paths, not just current one.
setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');
Notice the last / in the arguments.
From PHP manual:
The path on the server in which the
cookie will be available on. If set to
'/', the cookie will be available
within the entire domain . If set to
'/foo/', the cookie will only be
available within the /foo/ directory
and all sub-directories such as
/foo/bar/ of domain . The default
value is the current directory that
the cookie is being set in.
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script meaning there should be no html/code echo statements before that.
You won't be able to set the cookie server-side when using an AJAX call. Instead, wait until you get a successful response and set the cookie client side. To make it easier, you could use a jQuery plugin.