Last time, we showed you how to set up alternate color schemes using PHP. As promised, we will now show you how to remember the user’s choice.

We will once again make use of PHP, this time cookies. We will explore how to set the cookie for the user’s choice, and two methods of using this information.

First, we shall create a file. For purposes of demonstration, this file shall be called switch.php.

This file takes in a parameter color, sets the cookie value to that color, and redirects the user to the previous page. You can use other nomials than color if you wish.

	$color = $_GET['color'];
	$_COOKIE['color'] = $color;
	header("Location: " + $_SYSTEM['HTTP_REFERER']);

Next, we need to add links. The URLS will call switch.php with the relevant color.

<a href="switch.php?color=red">Red scheme<a>

When a user clicks on the link, the cookie will be set that their choice is their preferred scheme.

Now let’s look at ways of calling this information and showing the right scheme to the user.

Method One

The first method requires that your HTML page be done in PHP.

First, let’s look at the call to the CSS file from last time:

<link rel="stylesheet" type="text/css" file="styles.php?color=green" />

What we want to do is make the color variable and not hard-coded. We’ll look for the user’s cookie for this site called color. Remember that you may name it whatever you choose.

	$color = $_COOKIE['color'];
	echo '<link rel="stylesheet" type="text/css" file="styles.php?color='.$color.' />';

Method Two

The second method requires that your CSS file be done in PHP, which it already is. It allows for not passing any argument at all in the HTML page:

<link rel="stylesheet" type="text/css" file="styles.php" />

What this method does is call for the user preference in the CSS file.

In the CSS file from last time, there existed these three lines:

	$scheme-name = $_GET['color'];
	$scheme = $schemes[$scheme-name];
	if ( !$scheme ) { $scheme = $schemes['green']; }

We will replace the first line with the following:

	$scheme-name = $_COOKIE['color'];

By using one of these two methods, you can now remember the user preference and serve up different color schemes based on their preferences.

Leave a Reply

Remembering the User’s Preferred Color Scheme