Cookies and Sessions as a back up

I’m trying to create a script that works with cookies and sessions, i’m not sure if this is possible.

This is what i’ve got at the moment, but the session side of it doesn’t seem to work. Basically I want the session to remember a chosen theme, should the user have cookies disabled.



$theme = "";

if empty($_COOKIE['themeChoice']) {
	if (isset ($_GET['theme']) == "blue") {
		$_SESSION['theme'] = 'blue';
	} elseif (isset($_GET['setTheme']) == "red") {
		$_SESSION['theme'] = 'red';

$_SESSION['theme'] = $theme;

//checks if setTheme in address bar or cookie has been set
if (isset ($_GET['setTheme']) || isset($_COOKIE['themeChoice']) || isset($_SESSION['theme'])) {
	//if either value is blue
	if (($_GET['setTheme'] == "blue") || ($_COOKIE['themeChoice'] == "blue") || ($_SESSION['theme'] == 'blue')) {
		//set theme variable to blue
		$theme = "blue";
	//if either value is red
	} elseif (($_GET['setTheme'] == "red") || ($_COOKIE['themeChoice'] == "red") || ($_SESSION['theme'] == 'red')) {
	//set theme variable to red
		$theme = "red";
//if theme is already set and user has opted to change their current theme
if ($theme == "blue" && isset($_GET['changeTheme'])) {
		$theme = "red";
} elseif ($theme == "red" && isset($_GET['changeTheme'])) {
	$theme = "blue";
//set cookie for theme for next visit
setcookie("themeChoice",$theme, time()+3600*7);
//if the variable is empty (user hasn't come from choicePage nor has a cookie set) go to choicePage
if ($theme == ""){


And here is the html…

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">

<html class="no-js">


	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<link rel="stylesheet" type="text/css" media="all" href="css/<?php echo $theme; ?>.css" />

	<title>Insert title here</title>
	<script type="text/javascript" src=""></script>



	<div id="main">
		<div id="vertical"></div>
		<div id="logo">
			<img src="images/<?php echo $theme; ?>/logo.png">

	<p><a href="sessionindex.php?changeTheme">Choose a New Theme</a></p>
	<script type="text/javascript">



Any ideas? This is one of my first goes at PHP so please be nice.

I think my first question was a little complicated. Here it is simplified. How do I get the session to remember the variable?
First Page:



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

Goes to:


echo $_SESSION["theme"]?></p>

But this doesn’t echo out the colour depending on what what in the address bar on the previous page.


Your session setting code seems fine, I think you need to put session_start(); before echo also. So it would be like:

echo $_SESSION["theme"]

Hope this helps.


It’s quite possible - depending on your PHP configuration - that sessions aren’t working because you’ve disabled cookies (and sessions - by default - require cookies to work).
It is possible to propagate a session by passing th PHPSESSID in your URLs, but that just opens up a new attack vector on your site.

To be honest, IMO if people turn cookies off, including first-party cookies, then they simply can’t have a theme chooser :wink:

@Tapan: session_start() should go before any output. So your example would be better like this:

<?php session_start(); ?>
<?php echo $_SESSION["theme"]; ?>

// or:

echo '<p>' . $_SESSION["theme"] . '</p>';

Or even:


ya my bad, copied his code quickly and pasted :slight_smile:


I think you’re probably right. I guess I could just have a theme for those that don’t choose one. But the thing is I have a script that redirects the user if they haven’t chosen a theme, which is set by cookies. Like so:

if ($theme == ""){ 


Perhaps there is a way that when the user first chooses a theme, I can keep that ?setTheme=blue in the url for each wordpress page?

You could certainly do that, but it’ll be difficult to tack that onto all the links in your site.

I wonder, how many people actually disable first party cookies? Is it really worth all the hassle you’re going through now to try to support it?
Don’t get me wrong though, I think it’s very commendable of you :slight_smile:


For persistent type of data long-term storage I like to write it to the database as serialzed content. This way if a user deletes the cookies or the PHP server disposes of a users SESSION then their settings are still safe and remembered.

Then when a user visits, I check if their Session has the data if so I use it; otherwise I query the database to see if there is any saved session data and return and use this data also populating the SESSION with data so I minimize the calls to the DB. This way you can give the user more consistent permanency and you don’t have to worry about the cookies and SESSION saved states as much.


It probably isn’t worth it no. Especially my target audience, I’m not sure many of them would even know about cookies. I’ll just put a warning on the theme choice page saying something like, “Why do you keep seeing this page? Because you haven’t got cookies on!” - or something to that extent. Thanks for your reply.

This sounds good, but way to complicated for my current PHP abilities. I don’t have much of any idea about databases either. If you could point me towards a tutorial regarding this method, I’d be happy to take a look. Otherwise I can’t imagine myself working it out!
Thanks for your reply.


It really is not that tough. Here is what I recommend… pick up Rudy Limeback’s (r937) [COLOR=#000000]Sitepoint book ‘Simply SQL’ as it is a great starter book but will give you the basics on working with SQL.

Next I would learn how to use PDO ([/COLOR][COLOR=#000000])

Then learn how to use PHP serialize command

$session_data = null;
$session_data = $_SESSION;
$ready_for_db_session = serialize($session_data);
// Insert in table in database

My table in a database for this can be as simple as:

CREATE TABLE `serialized_data` (
  `id` int(11) NOT NULL auto_increment,
  `serialized_data` text,
  PRIMARY KEY  (`id`)


I then might have a user2serialized_data table where I link the user_id to the serialized_data id.

 //got $user_id when user logged in
 $sql ="
  JOIN [/COLOR][COLOR=#000000]user2serialized_data as u2sd[/COLOR]
[COLOR=#000000]    ON [/COLOR][COLOR=#000000] u2sd.user_id = $user_id;"[/COLOR][COLOR=#000000]


You retrieve this data and then run unserialize($serialized_data);

Then when a user logs in I get the user_id and go through to process that I described in my earlier post.

Hope this helps clarify it a little.



But… logging in without cookie support?

That would mean session id’s in URLs. I thought it was generally decided that that was bad, wasn’t it?


Yes that is bad, but what I was thinking but did not say is that when logging into a form the username and password would be held in $_POST. The action would post to a page that has the hash check with the SALT + USERNAME + PASSWORD hashed to verify. This way data never has to travel in the $_GET.

Using SSL (https) is also essential for important areas like logging in and handling of sensitive form and database data. Nowadays I do not do logins that are not secured by a Cert. Even for fun pet projects I generate my own, and the users of these systems know that they have to agree that they want to proceed when the browser challenges the validity of the self-made certificate. Even stolen email addresses are too important nowadays to not protect.


Was wondering…

IF a users browser is set to refuse all cookies, does the browser apply that rule to the Client Side LocalStorage facility as well?

Yes, but SESSION cookies are stored on the server whether or not the user has set the browser to refuse all cookies, so cookies can never really be totally turned off. It is very very hard to spoof a SESSION the hashing algorithm is advanced making it difficult, so hackers use easy vectors to get at what they want. Client side cookies are quite easy to spoof and to use in evil ways so, for that reason I never use them.


Sessions are stored on the server, the session cookie is stored in the browser.
It contains the session id, which PHP matches (on every request) to the session stored on the server.

No local cookies, no session.

Blocking cookies does block localStorage, in Chrome at least.

There’s always evercookies.

I’m more and more happy that NoScript offers selective disabling of various HTML5 thingies like canvas and WebGL.

Ahh didn’t know that … I guess that because I persist the users data in the database I can lay it out for them but based on what you are saying that is potentially a whole lot of connections to my db, because this process has to happen on each page request. Yuk! :frowning: Still works though.

That is a neat recommendation Stomme poes

Thanks for the replies guys. I’ll definitely have to think about it.
Only thing is that readers won’t actually log in to choose their theme, it will just depend on the cookie from when they last visited the site.
I don’t know if that changes your answer or not.

If ALL they’re setting is the theme - use the cookie. Someone wants custom themes, they need cookies… OH WELL.

Honestly I think people have been WAY too paranoid about the “evil cookies” because of all the hype, not realizing that 90% of the fun and useful websites out there wouldn’t work at ALL without them. PERIOD. Someone wants to be a paranoid tin-foil hat whacko and disable them completely, they get what’s coming to them; a crippled Internet where you can’t log into ANYTHING…

… including these forums.

Much of it can be blamed on tech article writers who are experts at writing, not tech – so they go for the sensational “cookies are evil” hype without even understanding what a cookie is, what good it serves, and how it really causes little if any REAL harm unless again, you’re a card carrying member of the tinfoil hat brigade where the government is beaming secret messages to your brain with their evil microwave towers.

As I’ve told more than one person who THINKS they’re tech saavy, taking technical advice from the pages of Forbes is like taking financial advice from Popular Electronics.