PHP Theme Switcher using a cookie
I want a simple way to update my sites CSS for broader accessibility.
I found this and it looks promising: http://php.about.com/od/finishedphp1/ss/css_switcher.htm
This is the PHP code it recommends:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Theme Test</title> <link rel="stylesheet" type="text/css" href="<?php echo (!$style)?'normal':$style ?>.css" /> </head> <body> <form action="changestyle.php" method="post"> <select name="choice"> <option value="classic" selected>Classic View</option> <option value="holiday">Holiday View</option> <option value="normal">Normal View</option> </select> <input type="submit" value="Go"> </form> </body> </html>
<?php $Year =31536000 + time(); setcookie ('style', $choice, $year); header("Location: $HTTP_REFERER"); ?>
However this fails as the stylesheet variable 'style' is apparently undeclared.
Am I missing something basic?
That tutorial is far from promising, aside from the fact that it's open to XSS vulnerabilities it doesn't even give you complete working code!
Try this for size...
<link rel="stylesheet" type="text/css" href="<?php echo (!isset($_COOKIE['style'])?'normal':$_COOKIE['style']) ?>.css" />
<?php $year = 31536000 + time(); setcookie('style', $_POST['choice'], $year); header('Location: index.php'); exit();
This won't solve your XSS problem (i.e. somebody changing the value of 'choice' to insert nasty code on your page) but should at least get it working.
For reference I would do a check in index.php to check the cookie matches a list of hard-coded values rather than just echo'ing out the value as anyone can change this (see What is Cross Site Scripting and How Can You Fix it?).