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;
}
Related
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
I read this article: http://smallbusiness.chron.com/hiding-url-parameters-php-redirect-33163.html
which explains how to but I'm don't understand how you redirect with the header as they say in there.
For storing in sessions this is code I use
session_start();
function input_val($key, $remember = true) { //use input_val('nameofinputfield')as value to be able to store in session
$value='';
if(isset($_REQUEST[$key])) {
$value = $_REQUEST[$key];
//Store value in session if remember = true
if($remember) {
$_SESSION[$key] = $value;
}
return $value;
} else {
//Return session data
return isset($_SESSION[$key]) ? $_SESSION[$key] : $value;
}
}
Let's say, you want to pass a username and email parameter from your script1.php to script2.php. If you are using POST method, in the URL the parameters won't show, and you can access your passed variables through $_POST global variable. But, if you want to use GET method for any reason, or you want to store data in $_SESSION you can do this.
You can try to use this in your script2.php:
session_start();
if (count($_GET)) {
foreach ($_GET as $key => $value) {
$_SESSION[$key] = $value;
}
header("Location: " . $_SERVER["PHP_SELF"]);
}
//At here, you can access all of your parameters from $_SESSOION variable
var_dump($_SESSION);
I will try to explain it as simple as I can, it's not that difficult.
When a user is in a session with the php he stores a little blob of text in the browser, this text is like a user ID that lasts until he close his browser. The php script can tell and extract information from the server, like parameters, by knowing his ID. This is not a cross-server feature though and it isn't persistent, unlike cookies, the expiration on the sessions are normally short and they expire when the user closes his browser.
Also it is recommended not to use it to store Get information like Page number, because it can't be re-referenced.
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.
This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.
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), "/");