views:

235

answers:

4

I want to pass a variable set by the user to the setcookie function. I would like to let user change the color of some parts of website. so far the information about color is sent to server with $_SESSION['colorcode'] and I would like to add it to setcookie as well so when the user logs in to the site next time, his/her color is there. I've got this code:

setcookie(
    'colorcode',
    $_SESSION['colorcode'],
    time() + 60 * 60 * 24 * 30,
    '',
    '',
    false,
    true
);

I would like to save the value of variable in cookie, but it works just for the session. what is wrong? how to do it so the color is there when the user logs in? I'm looking for another way than storing it in database or file.

A: 

Try to check this:

setcookie('colorcode',$_SESSION['colorcode'],time()+60*60*24*30);
Thinker
A: 

This should work just fine:

setcookie("colorcode",$_SESSION['colorcode'],time()+60*60*24*30);

Just make shure you output it in the headers, I guess:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

Do you get errors?

Jasper
no errors. do cookies have to be the very first line in script or could i have in fron of it this? : <?php require_once("classes.php");session_start();?>
perfectDay
session_start has to be completely firstthe cookies should be made before any output is made, which means in short, before any echo or print
Jasper
A: 
farzad
+1  A: 

Did you read back the value from the cookie at the beginning of the next session? Setting the cookie looks good but I think the last parameters could be omitted.

setcookie("colorcode", $_SESSION['colorcode'], time()+3600*24*30, '/');

Perhaps even the path ('/') is optional. But this only sets the cookie. You have to read the data back in, when the user returns to your site the next time.

if ( !isset($_SESSION['colorcode']) and isset($_COOKIE['colorcode']) ) {
    if ( preg_match('/^#?[0-9a-fA-F]{6}$/', $_COOKIE['colorcode']) ) {
        $_SESSION['colorcode'] = $_COOKIE['colorcode'];
    } else {
        // bad value... delete cookie if you like
    }
}

When there is no colorcode in the session but the cookie-value exists, then the data is validated and if it's a valid 6 digit hex color code, then the value is inserted into the session. The validation is nessessary because a cookie is data that comes from the user and therefore potentially malicious.

Uwe Mesecke