Setting Cookies

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gplev
Forum Newbie
Posts: 2
Joined: Wed Aug 29, 2007 8:26 am

Setting Cookies

Post by gplev »

Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Code: Select all

<?php

if (isset($_COOKIE["test"]))
  echo "Welcome " . $_COOKIE["test"] . "!<br />";
else
{
session_start();
$ses_id = session_id();
setcookie("test", $ses_id);
echo "New User";
}
?>
is there something with the way it is written. It seems that after I close out of IE or Firefox. The cookie is lost or is reset. Any ideas.


Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
xpgeek
Forum Contributor
Posts: 146
Joined: Mon May 22, 2006 1:45 am
Location: Kyiv, Ukraine
Contact:

Post by xpgeek »

You don't need to set cookie.
Use $_SESSION variable to store session variables.
Cookies would sent automatically.
gplev
Forum Newbie
Posts: 2
Joined: Wed Aug 29, 2007 8:26 am

Post by gplev »

so how I rewrite this script to do that.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Setting Cookies

Post by RobertGonzalez »

gplev wrote:

Code: Select all

<?php

if (isset($_COOKIE["test"]))
  echo "Welcome " . $_COOKIE["test"] . "!<br />";
else
{
session_start();
$ses_id = session_id();
setcookie("test", $ses_id);
echo "New User";
}
?>
is there something with the way it is written. It seems that after I close out of IE or Firefox. The cookie is lost or is reset. Any ideas.
Yeah, I have an idea. You are setting a browser session lifetime cookie. That means that the cookie will stay alive as long as the browser window is open. Once the browser closes, all browser session cookies get canned by the browser.

Read the manual on setcookie(). There is a pretty good amount of information about how to set cookies and cookie expiry times.
Post Reply