tags:

views:

244

answers:

4

I currently have a web site where users can select a custom theme. After they choose the theme, a cookie is created. The cookie contains the correct data and points to the correct CSS file. For some reason, upon re-visiting the site, the theme is not loaded. I should point out that I am new to PHP so it may be a very easy mistake. Please help. Thank you.

Here is my code:

<?php
$stylesArr = array('Default', 'Black', 'Pink', 'Green', 'Red');
if(isset($_GET['theme']) && in_array($_GET['theme'], $stylesArr)) {
    $style = 'CSS/' . $_GET['theme'] . '.css';
    setcookie("theme", $style, time()+(60*60*24*30));
} else {
    if(isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $stylesArr)) {
        $style = 'CSS/' . $_COOKIE['theme'] . '.css';
    } else {
        $style = 'CSS/Default.css';
    }
}
?>
<link rel="stylesheet" href="<?php echo $style>" type="text/css"media="screen" />
A: 

Try setting the $path parameter in your setcookie() call. If you don't set it, it defaults to the current directory. In this case, you want the cookie to be sitewide, so try this:

setcookie("theme", $style, time()+(60*60*24*30), '/');

You also need to be sure that the setcookie() call occurs before any other output. If you have this in your page below some HTML or any other output (including whitespace or anything not between <?php ?> tags), then setcookie() won't work.

zombat
Ok, I just tried what you said and also made sure the PHP code was at the top, but still no luck...
Nate Shoffner
+6  A: 

You are putting a string CSS/Default.css into a cookie, but then you are checking against string Default from $stylesArr. Change this line:

$style = 'CSS/' . $_GET['theme'] . '.css';

to this:

$style = $_GET['theme'];

and it will be okay.

Also, I must warn you about using data directly from $_GET in your application. You should never do that, because it can lead to severe security problems. Always sanitise user input.

n1313
A: 

You'll need to make sure you've already called session_start() right at the start of your script.

Ciaran McNulty
He's using his own cookie not the session cookie. This answer is wrong.
OIS
A: 

Off topic, but I would write that code more like this:

define('MONTH_IN_SECONDS', 2592000);
$themes = array('Default', 'Black', 'Pink', 'Green', 'Red');
$theme = reset($themes); //first value is default
if (isset($_GET['theme']) && in_array($_GET['theme'], $themes, true)) {
    $theme = $_GET['theme'];
    setcookie("theme", $theme, time()+ MONTH_IN_SECONDS);
} elseif (isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $themes, true)) {
    $theme = $_COOKIE['theme'];
}
$themeURL = 'CSS/' . $theme . '.css';
OIS