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.
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 can log in and access all member pages, but when I log out, I can still access all memberspages
I use this code to log out:
$_SESSION["admin_id"] = false;
$_SESSION["username"] = null;
redirect_to("login.php");
and this code to check if a user is logged in,
function logged_in() {
return isset($_SESSION["admin_id"]);
}
function confirm_logged_in($page) {
if (!logged_in()) {
redirect_to($page);
}
}
he redirects me after i have used the log out code. But i can still type in the member page URL and access them like I am logged in. I use an other webbrowser its impossible, so the pages are protected correctly. Or do I need to destroy the cookie and session complectly?
Here's what you're doing when you logout.
You are setting admin_id to false (which is technically a value).
$_SESSION["admin_id"] = false;
You then check to see whether admin_id is set:
isset($_SESSION['admin_id'); // returns TRUE because it "IS SET" to false
Options
You can either check whether admin_id is not empty (which handles null, false, 0).
function logged_in() {
return ! empty($_SESSION["admin_id"]);
}
You can extend your current function.
function logged_in() {
return isset($_SESSION["admin_id"] && $_SESSION["admin_id"] !== false);
}
You can set the variable to null.
$_SESSION['admin_id'] = null;
You can destroy the session completely.
session_destroy();
In place of:
$_SESSION["admin_id"] = false;
Try this:
unset($_SESSION["admin_id"]);
If you really need to log out, in my opinion your best option is to invalidate the session with a simple session_destroy().
By doing this you can check $_SESSION with the isset() function without problems, since every parameter belonging to the old session has been unset.
I'm sorry to trouble you, I have tried my best to solve this but I am not sure where I am going wrong and I was wondering if someone out there would be willing to help!
Basically, I am having some issues with $_SESSION variables; I would like for each occasion that a visitor came to the page that they would be shown a different content message.. The below code, when first landing on a page will seem to skip the first "content1", and will display "content2" instead, then "content3" after another revisit. I've put in an unset call, which eventually sends it there, am I not using _SESSIONS correctly?
I'm not sure how the session variable was assigned to 1, for it to land correctly in the if===1 statement without it first returning the original "content1"
if (empty($_SESSION)) {
session_start();
}
if (!isset($_SESSION['content'])) {
$content = "content1";
$_SESSION['content'] = 1;
return $content;
}
elseif ($_SESSION['content'] === 1) {
$content = "content2";
$_SESSION['content'] = 2;
return $content;
}
elseif($_SESSION['content'] === 2) {
$content = "content3";
unset($_SESSION['content']);
return $content;
}
Apologies for babbling or whether this was a simple fix / misunderstanding on my part. It's caused quite a headache!
Many thanks.
-edit-
This is a function that is called from within the same class, it has not gone through a loop anywhere either..
You are only calling session_start(); if the session has not been created.
What about the other times, when it's 1, or 2?
Call session_start(); regardless of your if (empty($_SESSION)) { statement
You should always use the session_start() function. If a session exists, it will continue it, otherwise it will create a new session.
Your code can then be simplified to the following:
// Start/Resume session
session_start();
// Get content
function display_message()
{
if ( ! isset($_SESSION['content']))
{
$_SESSION['content'] = 1;
}
if ($_SESSION['content'] == 1)
{
++$_SESSION['content']; // Increment session value
return 'Content #1';
}
elseif ($_SESSION['content'] == 2)
{
++$_SESSION['content']; // Increment session value
return 'Content #2';
}
elseif ($_SESSION['content'] == 3)
{
unset($_SESSION['content']); // Remove session value
return 'Content #3';
}
}
// Display content
echo display_message();
However, if someone visits your page a fourth time, they will be shown the first message again (because the session value is no longer tracking what they've been shown).
Perhaps this sort of functionality might be handled better with by using a cookie to track this information?
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.
The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.