I am currently playing around with cookies in my website, the first thing I do is run a check as to whether the user has cookie, if they dont I display a menu wth 3 options if they click it creates a cookie, but if then quit the browser the cookie is destroyed, here is my code,
function createRandomId() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime() * 1000000);
$i = 0;
$unique = '';
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$unique = $unique.$tmp;
$i++;
}
return md5($unique);
}
function index() {
// $data is the array of data that is passed to views, setup it up
$data = array();
// We need to setup the cookie that will be used site, this will be used to cross reference
// The user with the options they have selected, to do this we first need to load the session model
// Check if the user has a cookie already, if they it means they have been to the site in the last 30 days.
if(!isset($_COOKIE['bangUser'])) {
// Get createRandomId() method and return a unique ID for the user
$unique = '';
// Setting the cookie, name = bangUser, the cookie will expire after 30 days
setcookie("bangUser", $unique, time() + (60*60*24*30));
$data['firstTime'] = TRUE;
} else {
$data['notFirstTime'] = TRUE;
}
// Load the view and send the data from it.
$this->load->view('base/index', $data);
}
function createCookie() {
// Function gets called when the user clicks yes on the firstTime menu.
// The purpose of this function is to create a cookie for the user.
// First we'll give them a unique ID
$unique = $this->createRandomId();
// With the unique ID now available we can set our cookie doing the same function as before
setcookie("bangUser", $unique, time() + (60*60*24*30));
// Now that the cookie is set we can do a 100% check, check that cookie is set and if it is redirect to
// to the homepage
if(isset($_COOKIE['bangUser'])) {
redirect('welcome');
}
}
Basically the index() function does the check and the createCookie creates a new cookie, can any one see any problems?
In your createCookie function, calling setCookie will not immediately add the value to the $_COOKIE superglobal - this array only holds the cookies present when the request was made (but you could store your new cookie value in the array anyway)
Also, if you want a session cookie which is destroyed when the browser quits, specify null for the expiration time. Alternatively, just use PHP's built in sessions.
You need to set the fourth parameter of setcookie ($path) to the absolute path of you're website. For example:
setcookie("bangUser", $unique, time() + (60*60*24*30), "/");
Related
I have a big problem in changing cookie value. I have buttom function to change(if exist)/create(if !exist) cookie and set value for it.
When i call function the session value changed, but not happened any change in cookie data.
function setToken($time = 0) {
global $value;
if (!isset($_COOKIE["name"])) {
setcookie("name", $value, time() + $time);
} else {
$_COOKIE["name"] = $value;
}
$_SESSION["name"] = $value;
}
What's wrong && What's should i do???
Assigning to the $_COOKIE global doesn't actually set the cookie in the browser. Always call setcookie.
Also, make sure that no content has been sent to the browser before you set the cookie. Cookies are set in the headers sent to the browser so cannot be set after content has started to be flushed.
From the manual:
Cookies will not become visible until the next loading of a page that
the cookie should be visible for. To test if a cookie was successfully
set, check for the cookie on a next loading page before the cookie
expires. Expire time is set via the expire parameter. A nice way to
debug the existence of cookies is by simply calling
print_r($_COOKIE);.
Update:
Your code works for me. But make sure you give a positive integer to your function setToken(). If you do not, the cookie will be immediately expired and not be shown!
If you want to change the cookie value, change your code:
function setToken($time = 0) {
global $value;
if (!isset($_COOKIE["name"])) {
setcookie("name", $value, time() + $time); // inital set
} else {
setcookie("name", $value); // change value
}
$_SESSION["name"] = $value;
}
I am trying to track the actions of all non-logged in users on my site. The aim is to store this activity so that I can add it to their profile when they do create an account.
I am using the Behaviour below to assign new users a cookie and use that cookie as the basis of a "temp user" row in my Users table. This way a user can straight away start interacting with my API.
This seems to work fine. However, I am seeing loads more "temp user" rows being created in my DB than I have visitors to the site - about 2500 compared with around 500 visits yesterday (according to Google Analytics).
Is there anything wrong with the behaviour below, or am I doing something else wrong? Is there a better way?
<?php
class ApplicationBehavior extends CBehavior
{
private $_owner;
public function events()
{
return array(
'onBeginRequest' => 'setCookies'
);
}
public function setCookies()
{
$owner = $this->getOwner();
if ($owner->user->getIsGuest() && !isset(Yii::app()->request->cookies['dc_tempusername'])):
$tempusername = genRandomString(20);
$tempuser = new User();
$tempuser->username = $tempusername;
$tempuser->email = "noemailyet#tempuser.com";
if (isset(Yii::app()->request->cookies['dc_tempusername'])) {
$tempuser->name = Yii::app()->request->cookies['dc_tempusername']->value;
} else {
$tempuser->name = "CookieBasedTempuser";
}
$tempuser->points = 1;
$tempuser->firstip = $_SERVER['REMOTE_ADDR'];
if ($tempuser->validate()) {
Yii::app()->request->cookies['dc_tempusername'] = new CHttpCookie('dc_tempusername', $tempusername);
$cookie = new CHttpCookie('dc_tempusername', $tempusername);
$cookie->expire = time() + 60 * 60 * 24 * 180;
Yii::app()->request->cookies['dc_tempusername'] = $cookie;
$tempuser->save();
} else {
echo CHtml::errorSummary($tempuser);
}
endif;
}
}
?>
Check if cookies are enabled first:
Check if cookies are enabled
If we're correct, every time you see that the user is a guest and does not have a cookie then you're creating a new temp user.
Why not check to see if a cookie is set first, if so then create the temp user?
You would end up needing to set 2 cookies: initial temp cookie to check against, and then your 'dc_tempusername' cookie.
You could even go as far as using Browscap to check against known bots:
https://github.com/browscap/browscap-php
http://browscap.org/
You'll need to be able to define browscap in your php.ini
I am having problems with the session_id() that returns a new value every time on browser refresh/restart.
Read this post here but it doesn't solve the issue.I did all that was mentioned there - browser accepts cookies, permissions are set correctly, no param value is changed on sequential requests, etc.
Could this be refered to not using the session_name() or session_set_cookie_params() correctly? Or maybe it is the initial configuration that should be fine-tuned?
public static function init_session($name = FALSE, $lifetime = 10, $path = '/', $domain = FALSE, $secure = FALSE)
{
if (empty($name))
{
$name = APP_NAME;
}
if (empty($domain))
{
$domain = BASE_URL;
}
session_name($name);
session_set_cookie_params($lifetime, $path, $domain, $secure, TRUE);
session_start();
echo session_id();
}
First of all, you set your session lifetime to 10 seconds, which means that you get a new session after every 10 seconds.
Side note: It's normal behaviour for some browsers to discard session cookies when closing the browser.
If you need your session to expand over multiple browser sessions, you need to use persistent cookies.
Example:
function init_session(/* ... */)
{
if(!isset($_SESSION)) {
session_start();
}
//Is it a running session?
if(isset($_SESSION['somevalue'])) {
//Everything is fine, session is loaded, no need to reload from cookies
} else {
if(isset($_COOKIE['yourcookiename'])) {
//reload session from cookie
} else {
create_session();
}
}
}
function create_session()
{
$_SESSION['somevalue'] = 1;
//setcookie
}
Read http://www.allaboutcookies.org/cookies/cookies-the-same.html
Does Php always create a session file as soon as session_start() is called, even though there's nothing to keep track of (= no variable written in $_SESSION[])? If so, why?
Default PHP file-based sessions encode the session ID into the session file's filename. Since that's the only place the ID is kept normally, SOMETHING has to be kept to store the id. That means you'll get a file created, even if nothing is EVER written to $_SESSION.
In PHP-like pseudo code, basically this is occuring:
function session_start() {
if (isset($_COOKIE[ini_get('session.name')])) {
// session ID was sent from client, get it
$id = $_COOKIE[ini_get('session.name')];
} else {
// no session ID received, generate one
$id = generate_new_id();
setcookie(ini_get('session.name'), $id, ......);
}
$session_file = ini_get('session.save_path') . '/sess_' . $id;
if (file_exists($session_file)) {
// found a session file, load it
$raw_data = file_get_contents($session_file);
$_SESSION = unserialize($raw_data);
} else {
// brand new session, create file and initialize empty session
file_put_contents($session_file, serialize(array());
$_SESSION = array();
}
// lock the session file to prevent parallel overwrites.
flock($session_file);
}
I'm writing a simple website which allows a user to login, fill out a form which is submitted to a database and then log out. In order to manage the session, I used the session manager which is described by TreeHouse on the following page: http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions
In order to protect against hijacking, the client's IP address and user agent are stored in the session variable and compared to the server's values for these properties on each page. If they don't match, then it is assumed that the session has been hijacked and it is reset.
The implementation seems to work on my local machine without any issues, but when I uploaded it to the server, each page refresh causes the preventHijacking() function to return false (meaning it believes the session has been hijacked). However, if I echo any text within that function, the problem mysteriously disappears and the whole thing works as I expect it to (except for the bit of echoed text which is now displayed above my form :P).
I haven't a clue why this would be the case and I can't figure out how to fix it. The session manager code is below. At the start of each page, I use this to start the session and then each page simply uses or sets whatever variables it requires. If anyone could suggest why the function always returns false unless it echoes text and perhaps suggest what modification I need to make so that it will behave in the expected manner, I'd really appreciate it.
<?php
class SessionManager {
protected static $timeout = 600; // Time before automatic logout for the session
static function sessionStart($name, $limit=0, $path='/', $domain=null, $secure=null) {
// Set the cookie name before we start
session_name($name.'_Session');
// Set the domain to default to the current domain
$domain = isset($domain)? $domain : $_SERVER['SERVER_NAME'];
// Set the default secure value to whether the site is being accessed with SSL
$https = isset($secure)? $secure : isset($_SERVER['HTTPS']);
// Set the cookie settings and start the session
session_set_cookie_params($limit, $path, $domain, $secure, True);
session_start();
// Make sure the session hasn't expired and destroy it if it has
if(self::validateSession()) {
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking()) {
// Reset session data and regenerate ID
$_SESSION=array();
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session ID changing on any request
} else if (rand(1, 100) <= 5) {
self::regenerateSession();
}
$_SESSION['LAST_ACTIVITY'] = time();
} else {
$_SESSION = array();
session_destroy();
session_start();
}
}
static function preventHijacking() {
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent'])) {
return false;
}
if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) {
return false;
}
if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
return false;
}
return true;
}
static function regenerateSession() {
// If this session is obsolete, it means that there already is a new id
if(isset($_SESSION['OBSOLETE']) && $_SESSION['OBSOLETE'] === True) {
return;
}
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = True;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
static protected function validateSession() {
// Check if something went wrong
if(isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
return false;
}
// Test if this is an old session which has expired
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
return false;
}
// Check if the user's login has timed out
if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > self::$timeout) {
return false;
}
return true;
}
}
?>
I could be way out here (it's been a while) but that sounds like the buffer containing the headers isn't being flushed for some reason. Providing body would force them to be flushed, so maybe not providing the body doesn't flush?
Try putting ob_end_flush(); in there before you return. That may fix it.