Dan382
Dan382

Reputation: 986

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:

index.php

<!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>

changestyle.php

<?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?

Upvotes: 0

Views: 1278

Answers (1)

fire
fire

Reputation: 21531

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...

index.php

<link rel="stylesheet" type="text/css" href="<?php echo (!isset($_COOKIE['style'])?'normal':$_COOKIE['style']) ?>.css" />

changestyle.php

<?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?).

Upvotes: 2

Related Questions