Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason why this code snippet wouldn't set a cookie properly?

This little PHP snippet is used to set a cookie that lets me determine whether or not a user is logged in. For some reason, after I use the javascript to redirect, none of my cookies are set any more. Any reason why this would be happening?

I may not be giving you enough info so let me know if so.

...some database queries...
<?php 
    $expire=time()+(7 * 24 * 60 * 60);
    $row = mysql_fetch_array($query);
    $email = $row['email'];
    $userinfo['name'] = $name;
    $userinfo['email'] = $email;
    $userinfo = serialize($userinfo);
    setcookie("user", $userinfo, $expire);
    echo '<script type="text/javascript">
        window.location = "../index.php";
    </script>';

?>
like image 774
tnw Avatar asked Jan 20 '23 01:01

tnw


1 Answers

Tory, make sure you do not output anything before you call set setcookie in PHP. Not even white space. No echo. Nothing. What I guess is your scripts outputs some thing before setcookie and that breaks your script. Do you see header already sent error? Comment out your JS and then check. You setcookie in this way

setcookie(name,value,expire,path,domain,secure); 

Domain needs a domain name value in string like example.com, its optional. Secure needs a boolean value and is optional. Skip these two and check by setting path to '/'

like image 103
Kumar Avatar answered Feb 08 '23 16:02

Kumar