Background and Text Color Switch

Background and Text Color Switch
Last time I posted a small project written in PHP about a Background and Text Color Switcher. It wasn’t working right at that time as you can see, we were having some trouble keeping the values of the variables that keep the color changes stay. We have to keep it so that on next page reload, the colors won’t revert back to the defaults. And, after some research and resource gathering, I finally manage to find the solution.

In order to keep the values, it has to be stored in a super variable such as a SESSION or a COOKIE. In this case, I choose SESSION. Now, the previous code was a mess, although I create SESSION instructions, it wasn’t actually in the right order, that’s why the function kinda executed in an undesirable way. So I switch some of the codes and place it in the proper order. I also added an additional switch that has no submit button for the themes (color sets). Then, I created session instructions that unsets and destroys the session variable after 30 minutes or 1800 secs. This is so that the settings won’t stay the same forever.

By the way, here is the link to the PHP File:

Link to: Background and Text Color Switch (Demo PHP)

Source Code Talk

Source Code
I’m going to explain how I manage to make it work so I’m going to dissect my code into pieces… First of all, let’s discuss this part:

	session_start();
	$selected = "selected=\"selected\"";
	$time = $_SERVER['REQUEST_TIME'];
	$timeout_session = 1800;
	if(isset($_SESSION['LAST_ACTIVITY']) && ($time - $_SESSION['LAST_ACTIVITY']) > $timeout_session) {
		session_unset();
		session_destroy();
		session_start();
	}
	$_SESSION['LAST_ACTIVITY'] = $time;

So what does it actually do?

OK, this part is set at the topmost part of the code and before everything else. The reason for that is so that it would be process first and with utmost priority. This is what the code means…

session_start() – starts the session. This marks the beginning of the session runtime.

Next is the:

$selected = "selected=\"selected\"";

This is a variable that we are going to use later for the forms. So that when the selected color is picked, the dropdown list won’t switch back to the default value. The variable is echoed in the Dropdown list so it would display selected=”selected”, and keep the form option selected.

Next is the variables for the session.

$time = $_SERVER['REQUEST_TIME'];
$timeout_session = 1800;

$time is a variable that is equivalent to the super variable $_SERVER. This is use as a counter since session start.

$timeout_session is the variable that contains the value 1800. Each count is equivalent to a second. 1800 is equivalent to 30 mins.

As for:

if(isset($_SESSION['LAST_ACTIVITY']) && ($time - $_SESSION['LAST_ACTIVITY']) > $timeout_session) {
session_unset();
session_destroy();
session_start();
}

This is what it means… if $_SESSION[‘LAST_ACTIVITY’] variable is set and $time minus User’s last activity is greater than the set timeout elapsed time, then session will unset, destroy and restart a new one.

In other words, it is looking for the user’s last activity timestamp. If it’s set (or found) and indicates that the timeout duration has passed, then we instruct the server to erase any previous $_SESSION data and begin with a new one.

Finally…

$_SESSION['LAST_ACTIVITY'] = $time;

Which is used to update last activity so that our timeout is based on it and not on the user’s login time.

Now that we have set these session conditions, we go to the Background and Text Color Switch function.

I will be commenting on each code set as we go through the code… (Please refer to our PHP file)

if(isset($_POST['theme'])) { /* <-- Variable for the theme. It is use by the third Dropdown List Switch. */

/* If Theme is set, the server will be instructed to erase all session data and restart a new one, thus: */
		session_unset();
		session_destroy();
		session_start();

/* foreach defines the variable $_POST['theme'] as a variable with the name $theme. */
		foreach ($_POST['theme'] as $theme );

/* if the $theme variable is set to the following (ie. Currant, Flora, or Obsidian) value by the Dropdown list switch... */
		if($theme == "currant") {
/* then it will change the value of variables $bgcolor (background color) and $txtcolor (text color) to the following color values base on their respective theme... */
			$bgcolor = "#2E183B";
			$txtcolor = "#94899A";
		}
		if($theme == "flora") {
			$bgcolor = "#F8B5CC";
			$txtcolor = "#ED4580";
		}
		if($theme == "obsidian") {
			$bgcolor = "#0E0E0E";
			$txtcolor = "#A5A5A5";
		}
	}
/* the code below checks if changetxtcolor from submit button name is set or submitted, if it is, then use it, and set it as SESSION data as well. */
	if(isset($_POST['changetxtcolor'])) {
		foreach ($_POST['txtcolor'] as $txtcolor );
		$_SESSION['textcolor'] = $txtcolor;
/* else if there is no new value from post, use stored SESSION data if present (not empty) */
	} elseif (!empty($_SESSION['textcolor'])) {
		$txtcolor = $_SESSION['textcolor'];		
	} else {
/* else if SESSION data is also empty then use default text color. */
		if(empty($_POST['txtcolor'])) {
			if(!isset($theme)) { /* <-- As long as theme is not set then default color scheme will apply. */
				$_POST['txtcolor'] = "#000000";
				$txtcolor = $_POST['txtcolor'];
			}
		}
	}
/* the same instruction from text color function is applied on background color function. */
	if(isset($_POST['changebgcolor'])) {
		foreach ($_POST['bgcolor'] as $bgcolor );
		$_SESSION['backgroundcolor'] = $bgcolor;
	} elseif (!empty($_SESSION['backgroundcolor'])) {
		$bgcolor = $_SESSION['backgroundcolor'];
	} else {
		if(empty($_POST['bgcolor'])) {
			if(!isset($theme)) {
				$_POST['bgcolor'] = "#ffffff";
				$bgcolor = $_POST['bgcolor'];
			}
		}
	}

Ok, if the comments enclose in /* */ don’t make sense, here is what it means… In the PHP file, there are three forms, one for the Background Color, one for the Text Color, and one for the Theme. The forms use the variables $_POST[‘theme’], $_POST[‘txtcolor’], and $_POST[‘bgcolor’] respectively. It is written there that if Theme variable is set, then it will erase all session data and restart a new one. I made it that way so that when we switch the theme, it will force a color change, otherwise, the color values from bgcolor and txtcolor kept in a session (from a previous submission, if submitted) will persist and prevent the theme switcher from working.

Bgcolor and Txtcolor once submitted yields the color values they have and will store it in variables $txtcolor for $_POST[‘txtcolor’] (as defined by foreach) and $bgcolor for $_POST[‘bgcolor’]. After the setting of the variables, it also stores it in a session data (ie. $_SESSION[‘textcolor’] for text color and $_SESSION[‘backgroundcolor’] for background color so that after the post variables are loaded and emptied, the color change made by these functions will continue to apply, otherwise, they would reset back to default. Only theme and the timeout instruction can empty session data.

In the page’s stylesheet, I entered:

body {
		background-color: <?php echo $bgcolor . ";\n"; ?>
		color: <?php echo $txtcolor . ";\n"; ?>
	}
	p, form{
		color: <?php echo $txtcolor . ";\n"; ?>
	}
	h1 {
		color: <?php echo $txtcolor . ";\n"; ?>
		text-align: center;
	}

Notice the PHP echo codes in the stylesheet? Yes, they display the variables’ output for the background color and text color. This is how PHP modifies the page’s color styles.

As for the forms, I will only focus on certain key parts since it’s big…

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">Change Background Color:<br/><select size="1" name="bgcolor[]" required="required">

PHP echo $_SERVER[‘PHP_SELF’] is a global variable that means load the same page. For instance our url address is /archive/projects/backgroundcolorandtext.php, if we use PHP_SELF then it will reload that same url upon form submission. The selector name “bgcolor[]” refers to $_POST[‘bgcolor’].

Now let’s go to this part:

<option value="#ffffff" <?php if(isset($bgcolor)) { if($bgcolor == "#000000") { echo $selected;} else { echo "";}}?>>Black</option>

The code above means that if bgcolor variable contains the color value #000000 (black), then it will call for the $selected variable, that if you guys remember, contains selected=”selected”; thus keeping this form option selected once chosen. Otherwise, the dropdown list will switch back to the first option in the list.

Now, in our PHP file, two forms have Submit buttons, however, for the third form, there is no submit button. The form submits by just picking a value from its dropdown list. To make this possible we use:

<select size="1" id="thema" name="theme[]" onchange="this.form.submit()">

Note onchange=”this.form.submit()“. It’s actually a javascript that forces the form to submit if there is a change in the selection, for instance, from option “Please Select”, you select another value (ie. “Currant”) in the dropdown list option. Upon selecting “Currant”, the form will submit the value even without having you to press the Submit Button.

Here is our complete code:

<?php
	session_start();
	$selected = "selected=\"selected\"";
	$time = $_SERVER['REQUEST_TIME'];
	$timeout_session = 1800;
	if(isset($_SESSION['LAST_ACTIVITY']) && ($time - $_SESSION['LAST_ACTIVITY']) > $timeout_session) {
		session_unset();
		session_destroy();
		session_start();
	}
	$_SESSION['LAST_ACTIVITY'] = $time;
	if(isset($_POST['theme'])) {
		session_unset();
		session_destroy();
		session_start();
		foreach ($_POST['theme'] as $theme );
		if($theme == "currant") {
			$bgcolor = "#2E183B";
			$txtcolor = "#94899A";
		}
		if($theme == "flora") {
			$bgcolor = "#F8B5CC";
			$txtcolor = "#ED4580";
		}
		if($theme == "obsidian") {
			$bgcolor = "#0E0E0E";
			$txtcolor = "#A5A5A5";
		}
	}
	if(isset($_POST['changetxtcolor'])) {
		foreach ($_POST['txtcolor'] as $txtcolor );
		$_SESSION['textcolor'] = $txtcolor;
	} elseif (!empty($_SESSION['textcolor'])) {
		$txtcolor = $_SESSION['textcolor'];		
	} else {
		if(empty($_POST['txtcolor'])) {
			if(!isset($theme)) {
				$_POST['txtcolor'] = "#000000";
				$txtcolor = $_POST['txtcolor'];
			}
		}
	}
	if(isset($_POST['changebgcolor'])) {
		foreach ($_POST['bgcolor'] as $bgcolor );
		$_SESSION['backgroundcolor'] = $bgcolor;
	} elseif (!empty($_SESSION['backgroundcolor'])) {
		$bgcolor = $_SESSION['backgroundcolor'];
	} else {
		if(empty($_POST['bgcolor'])) {
			if(!isset($theme)) {
				$_POST['bgcolor'] = "#ffffff";
				$bgcolor = $_POST['bgcolor'];
			}
		}
	}
?>
<html>
<head>
<title>Background and Text Color Switch | Altometa</title>
<meta name="description" content="A simple PHP program that demonstrates how PHP can change the background color and text color of the page using a Dropdown switch." />
<meta name="robots" content="index,follow" />
<meta name="keywords" content="background color, text color, background and text color" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
	body {
		background-color: <?php echo $bgcolor . ";\n"; ?>
		color: <?php echo $txtcolor . ";\n"; ?>
	}
	p, form{
		color: <?php echo $txtcolor . ";\n"; ?>
	}
	h1 {
		color: <?php echo $txtcolor . ";\n"; ?>
		text-align: center;
	}
</style>
</head>
<body>
	<h1>Background and Text Color Switch</h1>
	<p>This is a demonstration to show how PHP can manipulate the colors of the background of the page as well as change the color of the texts.</p><br/>
	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><br/>
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">Change Background Color:<br/><select size="1" name="bgcolor[]" required="required">
		<option value="#ffffff" <?php if(isset($bgcolor)) { if($bgcolor == "#ffffff") { echo $selected;} else { echo "";}}?>>White</option>
		<option value="#000000" <?php if(isset($bgcolor)) { if($bgcolor == "#000000") { echo $selected;} else { echo "";}}?>>Black</option>
		<option value="#ff4500" <?php if(isset($bgcolor)) { if($bgcolor == "#ff4500") { echo $selected;} else { echo "";}}?>>Red Orange</option>
		<option value="#ffb6c1" <?php if(isset($bgcolor)) { if($bgcolor == "#ffb6c1") { echo $selected;} else { echo "";}}?>>Peach</option>
		<option value="#008080" <?php if(isset($bgcolor)) { if($bgcolor == "#008080") { echo $selected;} else { echo "";}}?>>Teal</option>
		<option value="#8db600" <?php if(isset($bgcolor)) { if($bgcolor == "#8db600") { echo $selected;} else { echo "";}}?>>Apple Green</option>
		<option value="#00ffff" <?php if(isset($bgcolor)) { if($bgcolor == "#00ffff") { echo $selected;} else { echo "";}}?>>Cyan</option>
		<option value="#654321" <?php if(isset($bgcolor)) { if($bgcolor == "#654321") { echo $selected;} else { echo "";}}?>>Dark Brown</option>
		<option value="#008000" <?php if(isset($bgcolor)) { if($bgcolor == "#008000") { echo $selected;} else { echo "";}}?>>Green</option>
		<option value="#ff0000" <?php if(isset($bgcolor)) { if($bgcolor == "#ff0000") { echo $selected;} else { echo "";}}?>>Red</option>
	</select>
	<input name="changebgcolor" type="submit" value="Submit" />
	</form>
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">Change Text Color:<br/>
	<select size="1" name="txtcolor[]">
		<option value="#ffffff" <?php if(isset($txtcolor)) { if($txtcolor == "#ffffff") { echo $selected;} else { echo "";}}?>>White</option>
		<option value="#000000" <?php if(isset($txtcolor)) { if($txtcolor == "#000000") { echo $selected;} else { echo "";}}?>>Black</option>
		<option value="#ff4500" <?php if(isset($txtcolor)) { if($txtcolor == "#ff4500") { echo $selected;} else { echo "";}}?>>Red Orange</option>
		<option value="#ffb6c1" <?php if(isset($txtcolor)) { if($txtcolor == "#ffb6c1") { echo $selected;} else { echo "";}}?>>Peach</option>
		<option value="#008080" <?php if(isset($txtcolor)) { if($txtcolor == "#008080") { echo $selected;} else { echo "";}}?>>Teal</option>
		<option value="#8db600" <?php if(isset($txtcolor)) { if($txtcolor == "#8db600") { echo $selected;} else { echo "";}}?>>Apple Green</option>
		<option value="#00ffff" <?php if(isset($txtcolor)) { if($txtcolor == "#00ffff") { echo $selected;} else { echo "";}}?>>Cyan</option>
		<option value="#a52a2a" <?php if(isset($txtcolor)) { if($txtcolor == "#a52a2a") { echo $selected;} else { echo "";}}?>>Brown</option>
		<option value="#008000" <?php if(isset($txtcolor)) { if($txtcolor == "#008000") { echo $selected;} else { echo "";}}?>>Green</option>
		<option value="#ff0000" <?php if(isset($txtcolor)) { if($txtcolor == "#ff0000") { echo $selected;} else { echo "";}}?>>Red</option>
	</select>
	<input name="changetxtcolor" type="submit" value="Submit" />
	</form>
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">Select a Theme:<br/>
	<select size="1" id="thema" name="theme[]" onchange="this.form.submit()">
		<option value="none">Please Select</option>
		<option value="currant" <?php if(isset($theme)) { if($theme == "currant") { echo $selected;} else { echo "";}}?>>Currant</option>
		<option value="flora" <?php if(isset($theme)) { if($theme == "flora") { echo $selected;} else { echo "";}}?>>Flora</option>
		<option value="obsidian" <?php if(isset($theme)) { if($theme == "obsidian") { echo $selected;} else { echo "";}}?>>Obsidian</option>
	</select>
	</form>
	<br/><br/>
</body>
</html>

Feel free to discuss if you guys have questions or feed backs.

Follow me at:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.