In this tutorial you use some basic scripts in order to store and retrieve informations from a cookie. The information consists in the name of the css chosen by the user.
Here's how it works:
Each page use some line of php code in order to correctly show different styles.
Inside the <head> you have to put these code lines:
<?
$pageURL = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
require "showcss.php";
?>
The first line is used to store current page name inside the $pageURL variable. That will be used by setcsscookie.php to correctly redirect to the page which launched the script.
The second line just load showcss.php code (it is useful to use the require function if you need the same script in different pages).
Each link to a different style is in this form:
<a href= "setcsscookie.php?id=nameofthecss&page=<?echo $pageURL;?>">default</a>
As you can see the link call setcookie.php with two parameters:
This script is used to set a cookie in order to store the style preferences so that it remains the same when the user browse in different pages:
<?
setcookie("css", $_REQUEST['id']);
header("Location:{$_REQUEST['page']}");
?>
The parameters of setcookie() function are:
The second line use the header() funciton to automatically redirect the user to the page from which the script was activates (which corresponds to the variable page sent the same way as explained above).
This script is used in each page and it's loaded using the require statement.
<?
if(isset($_COOKIE['css'])){
$id= $_COOKIE['css'];
echo '<link rel="stylesheet" type="text/css" href="'.$id.'.css" />';
}else{
echo '<link rel="stylesheet" type="text/css" href="esempio1.css" />';
}
?>
This script consists of an if-else statement that check if a cookie named css is set.
If the cookie has been already set it loads the css with the name stored in, else it loads the default css.
So, each time a page loads, showcss.php checks which css has to be used. User via a link can choose among different stylesheets by clicking and thus activating setcsscookie.php to store the stylesheet's name.