Cookies and Sessions as a back up

where the government is beaming secret messages to your brain with their evil microwave towers.

it’s not the government, man, it’s, like, the corporations

[COLOR=#000000][FONT=monospace]bo5ton,

This thread may be getting a little ‘long in the tooth’ for you and likely from all the examples you have figured out what you need to do, However given that the user’s theme will be based on what they last chose during one time they were logged in, and didn’t have cookie support disabled, and didn’t clear their cookie cache after their visit then it is simply:[/FONT][/COLOR][COLOR=#0000BB][FONT=monospace]


<?php  
session_start();
if($_SESSION["theme"]){
  // Do your theme stuff
} else {
  // Do default theme stuff because the session cookie does not exist
}
?>

Steve[/FONT][/COLOR]

That’s pretty much what i figured. However, as you can see in my first post, I was able to set the theme by getting the cookie or via the url($_GET) functions to = $theme; - But I’m not sure if I can do the same with ($_SESSION[“theme”]) = $theme - should this work ok?

As I first have to set the theme before I can see if it is set already. Something like:

if ($_GET['setTheme'] == "blue") {
($_SESSION['theme'] == "blue"
} elseif ($_GET['setTheme'] == "red") {
($_SESSION['theme'] == "red"
}

And then can I set the $theme variable depending on that session?

($_SESSION["theme"]) = $theme;

Thanks for all your replies guys. If I can’t get it to work, those without cookie enabled will just have to miss out on a fantastic new site!

Well, I can’t get it to work it seems. Even doing a small test I can’t get it to remember the theme chosen i.e. when i navigate away and back again, it resets.
Here’s my small test:

Page to choose theme:

<?php

session_start();

	if (($_GET['setTheme']) == "blue") {
		$_SESSION['theme'] = "blue";
	} elseif (($_GET['setTheme']) == "red") {
		$_SESSION['theme'] = "red";
	}
	
	?>
	
<a href="remember.php">test</a>

Page to show theme, both first time(which works) and when navigate away and come back (which doesn’t work):

<?php
session_start();
if($_SESSION['theme'] == "blue"){
  $theme = "blue";
} else {
  $theme = "red";
}
?>

<a href="#"><?php echo $theme; ?></a>

Almost ready to give up.

Hi Bo5ton

Please try the following…

I am providing you with a very simple Session wrapper class. It doesn’t change that you can not retrieve the stored theme value but does make handling a little easier. You will copy this into a file called Session.php, and for now store it next to the test.php that you will soon create.

Session Wrapper Class:
[rule=100%]Navy[/rule]


<?php
/**
* A wrapper around PHP's session functions
* <code>
* $session = new Session();
* $session->set('message','Theme is Red!');
* echo ( $session->get('message'); // Displays 'Theme is Red!'
* </code>
* @access public
*/

class Session {
    /**
    * Session constructor<br />
    * Starts the session with session_start()
    * <b>Note:</b> that if the session has already started, session_start()
    * does nothing
    * @access public 
   */
    public function __construct() {
        session_start();
    }
        
  /**
    * Sets a session variable
    * @param string name of variable
    * @param mixed value of variable 
   * @return void
    * @access public 
   */
    public function set ($name,$value) {
        $_SESSION[$name]=$value;
    }   
  /**
    * Fetches a session variable
    * @param string name of variable
    * @return mixed value of session variable
    * @access public
    */ 
   public function get ($name) {
        if ( isset ( $_SESSION[$name] ) ) 
           return $_SESSION[$name];
        else
            return false;
    }
    /**
    * Deletes a session variable
    * @param string name of variable
    * @return boolean
    * @access public
    */    public function del ($name) {
        if ( isset ( $_SESSION[$name] ) ) {
            unset ( $_SESSION[$name] );
            return true;
        } else {
            return false;
        }
    }
/**
    * Destroys the whole session
    * @return void
   * @access public
    */
    public function destroy () {
        $_SESSION = array();
        session_destroy();
    }
}
?>

in a test php file do this:

Test.php:
[FONT=arial][COLOR=#000000][rule=100%]Navy[/rule]


<?php
require_once('Session.php');
$o_Session = null;
$o_Session = new Session();
//$o_Session->del('theme'); /* <-- Uncomment this to delete the session */

//set cookie expiration to 1 hour ago; therefor deleting it.
//setcookie ('theme', '', time() - 3600); /* <-- Uncomment this to delete the cookie */

/*
 * Get Session theme and the theme cookie
 */
$theme = null;
$theme = $o_Session->get('theme');
$theme_cookie = null;
$theme_cookie = $_COOKIE['theme'];
if(!$theme_cookie){
  $o_Session->set('theme', 'red'); //set session  
 $time = null;
 $time = time() + 60*60*24*1000;
 setcookie('theme', $theme, $time); //set cookie with appropriate parameters}
?>
<html>
  <head></head>
  <body>
    <?php
     switch($theme_cookie){
       case 'red' :
         echo '<div style="background-color: red">This is a red div</div>';
         break;
       case 'blue':
         echo '<div style="background-color:blue">This is a blue div</div>';
          break;
        default: //Will get this if cookies turned off or have been deleted
           echo '<div style="background-color:green">This is the default colour</div>';
     }   ?>
  </body>
</html>

What do you get when you run the test.php page then close your browser, open it again and run?[/COLOR][/FONT]

Wow thanks, @ServerStorm;, I’ll give it a try and see how I go.

Great bo5ton,

Thanks for the mention… I wrote this out to help you get through the ‘almost had enough stage’, and also because I had not used cookies like this before so I wanted to see how it worked out. I now see what @Emerse was speaking about which was good to learn. So it also helped me doing this, even if this doesn’t work for you :slight_smile:

I tested these and it worked the way I think you were hoping. Obviously you will set the cookies as some type of theme picker elsewhere in your application but the general flow will be similar. You will also have to give them the opportunity to clear their SESSION and COOKIE.

When using cookies like that if you had logged-in accounts you would not let users change their passwords or usernames with just the stored cookie authentication. You would make them log in again to change any such important parameters.

I don’t use cookies, instead I retrieve serialized settings when users log in. If they clear the ‘remember my settings’ checkbox then I flush the settings so they go back to the default settings. Now after doing this exercise, I might just step out of the dark ages and use cookies when not doing important things; they are faster to implement than storing it and subsequent retrieval from the db. The db way is more secure though :slight_smile:

Regards,
Steve

Ah cool that makes sense.
I gave it a try, there was an error in test.php, but it was just the curly bracket that was on line 21 instead of 22, so it was commented out, fixed that.
I have tried it with cookies on, which works when setting the theme to red. however once it was red it would stay red ( i assume that’s what the deleting line is for). It didn’t work if i cleared cookies and set it to blue.
With cookies turned off, it didn’t seem to remember the theme I chose either.

@bo5ton

Hi,

Sorry about the bracket, when I copy code from eclipse into these windows it removes all the line breaks so I need to manually fix it so it is readable. In this process I must of nuked a bracket.

The reason that you couldn’t get blue to work is the sequence of how this test is setup. You must change the colour to blue first then uncomment and delete the cookie and session, then recomment the delete cookie and session and then run and you will get blue (which it will remember in between visits).

With cookies turned off, it didn’t seem to remember the theme I chose either.
Yes the cookie is what persists inbetween visits, the session only exits until it is explicitly cleared or when a users browser is closed and then the ‘time to live’ has exceeded for the session. This is what DeathShadow60 was referring to in post #20

The test script is brittle with hard-coded options, and the way that cookies and sessions are created but you will set a Session ‘theme’ and Cookie ‘theme’ variables in the theme picker area of your site. You will need to use some javascript (for an live css changes) or a redirect after they choose their theme as the page will have to load the new theme’s CSS.

Then you will have to create a way for them to clear their settings or ‘set defaults’, which amounts to clearing the theme variables.

Make sure that you also set a suitably long-time for the Cookies time an you may have to change the way your server SESSIONS are configured if you find things that you store in the session are disappearing (being disposed of by PHP automatically based on the php.ini session settings).

Regards,
Steve

… open firefox or ie and then run it… it should be red. Keep that browser open and then change the color to blue and open and view it with Chrome. Now refresh, shutdown and open the two browsers and you will see they maintain their own settings. This is the behaviour that you wanted.

Steve

Hi ServerStorm,
Thanks for all your hard work on figuring this out, however I still can’t get it to work.
I have uploaded my version of the files here so you can take a look at if it’s working as your example is.
Basically the only thing I can get to work is the red theme with cookies on.
I can’t get blue theme with cookies on, nor red or blue with cookies off (using session cookies).
Am I missing something?
I am supposed to be entering the url and then ?theme=blue at the end right?
Thanks again.

Hi bo5ton,

Originally I had not written the test using $_GET which is why it did not work when you uses “./?theme=blue” in the url.

I re-wrote this so it now works the way you need. Please keep in mind that I did this quickly with not much thought for efficiency. Just looking it over, having to re-output the same HTML content in the switchers stinks to me. You might want to put the switcher into it’s own function and then call it for either switch. This is just a test.

The reason that the if($selected_theme) else $theme_cookie, is a user if having selected a theme can simply use their selected choice in the $_GET variable to set the theme immediately. However the $theme_cookie side of this if, uses the stored cookie.


<?phprequire_once('./libs/common/Session.php');
$o_Session = null;
$o_Session = new Session();

if($selected_theme){
  $o_Session->set('theme', $selected_theme); //set session
}
function storeTheme($selected_theme){
  if($selected_theme){
    $time = null;
    $time = time() + 60*60*24*1000;
    setcookie('theme', $selected_theme, $time); //set cookie with appropriate parameters 
 }
}
/*
 * Uncomment these and run the script to delete the session and cookie
 */
//$o_Session->del('theme');
//setcookie ('theme', '', time() - 3600); //set cookie expiration to 1 hour ago
$selected_theme = null;
$selected_theme = htmlentities($_GET['theme']);
$theme_cookie = null;
$theme_cookie = $_COOKIE['theme'];
$theme_session = null;
$theme_session = $o_Session->get('theme');
if($selected_theme){
  storeTheme($selected_theme);
}
?>
<html>
  <head>
  </head>
  <body>
      <a href='test4.php?theme=red'>red</a><br />
      <a href='test4.php?theme=blue'>blue</a>
    <?php
     if($selected_theme){
       switch($selected_theme){
         case 'red' :
           echo '<div style="background-color: red">This is a red div</div>';
           break;
         case 'blue':
           echo '<div style="background-color:blue">This is a blue div</div>';
           break;
        default: //Will get this if cookies turned off or have been deleted
         echo '<div style="background-color:green">This is the default colour green div</div>';
       }
     } else {
       switch($theme_cookie){
         case 'red' :
           echo '<div style="background-color: red">This is a red div</div>';
           break;
         case 'blue':
           echo '<div style="background-color:blue">This is a blue div</div>';
           break;
          default: //Will get this if cookies turned off or have been deleted
         echo '<div style="background-color:green">This is the default colour green div</div>';
       }
     }
   ?>
  </body>
</html>

Steve