Hi, I'm having a basic issue with cookies If I echo the $_COOKIE['username'] after its created, it displays correctly: <?php setcookie(username, time()+3600); $_COOKIE['username'] = 'user'; echo 'User name is ' . $_COOKIE['username'] . '<br>'; // this would display 'User name is user', like it should. ?> PHP: However, if at any point later I echo the cookie, like so: <?php echo $_COOKIE['username']; ?> PHP: The following is displayed: '1219612645' I have no idea why. Can someone tell me what is wrong and how to fix it? Thanks!
The answer is not as simple as the question First of all, you did not set the cookie in the right way. How do you know that? If you use FireFox, install the Web Developer toolbar. http://chrispederick.com/work/web-developer/ In the Cookie menu you can see what you set for that cookie. Let's compare the cookie after your code and after my code. The value of the cookie['username'], in your case, was a random value. Your first program displayed what you want, because your forced it to. It had nothing to do with cookies. $_COOKIE['username'] = 'user'; echo 'User name is ' . $_COOKIE['username'] . '<br>'; PHP: You could have said: $myvariable = 'user'; echo 'User name is ' . $myvarialbe . '<br>'; PHP: and the output would have been the same. The second program displayed the real value of the cookie['username'], which you didn't set, and which was randomly "set" by the browser. The correct way to do this is: - In the first file: <?php setcookie('username', 'user', time()+3600); ?> PHP: Compare to: setcookie(username, time()+3600); PHP: Your original program used 2 parameters instead of three. It was equivalent to: setcookie('username', $random_value, time()+3600); PHP: By the way, you should use 'username' inside the quotes. - In the second file: <?php echo $_COOKIE['username']; ?> PHP: Please cofirm if it worked after the changes.
OK, lets say that the username is stored in a variable called $username. I would like the cookie to contain the value that the variable $username contains. How do I do this? Thanks for helping!