Setting and Retrieving Cookies

I am trying to do a very simple thing, which is fill in a login form (username and password) and store the username in a cookie. I would then like to retrieve and display the username on the page. The form posts back to the same page.

In the file header I have the following (I had a printf statement in the code to check that $value exists and it does):

if ($_POST["username"]) {
    $value = $_POST["username"];
    setcookie("un", $value, (time()+3600*24)*7);    
}

In the body of the file I have:

printf($_COOKIE["un"]);

Nothing prints.

As always, your help would be much appreciated.

[php] if ($_POST[“username”]) {
$value = $_POST[“username”];
setcookie(“un”, $value, time()+3600247);
}[/php]

I cant edit my post for some reason :confused:

This is how I use cookies.

[php]setcookie (‘un’, $_POST[‘username’], time()+3600247, ‘/’, ‘’);
echo $_COOKIE[‘un’];[/php]

Thanks “lothop”, but still no joy. I don’t know what else to try. Any other ideas? PLEASE

Your if statement is bad.
[php]if(isset($_POST[‘username’])) {
setcookie (‘un’, $_POST[‘username’], time()+3600247, ‘/’, ‘’);
}else{
echo(‘please enter a username’);
}[/php]

If that doesn’t work try [php]echo $value;[/php] to see if it outputs it ok.

I Have now put the follow in the Header:

if($_POST['username']) {
	setcookie ('un', $_POST['username'], time()+3600*24*7, '/', '');
	echo("Got here");
}

The If statement is fine as I am getting the echo of “Got here”.

From some reading I have done I understand that the cookie must be set in the header and that it can only be read in subsequent pages.

I have thefore put a link to another page on the page where I set the cookie and on the second page (on the same domian), have the following code:

				if(isset($_COOKIE['un']))
				{ 
				$last = $_COOKIE['un']; 
				echo "Welcome back! <br> You last visited on ". $last; 
				} 
				else 
				{ 
				echo "Welcome to our site!"; 
				} 

The cookie is still not set.

HELP !!!

PROBLEM SOLVED

the setcookie must come at the very beginning of the pages code - even BEFORE the tag.

Thank you “lothop” for trying to help.

Ah k, glad you got there in the end. I have never tried to set a cookie in a page with, I always use a form processing page.

also the cookie can only be read in subsequent pages because the cookie is being set as the page is already being rendered, if you really want that cookie on that page right then, then you need to do a quick after setting the cookie, so the page will refresh really quick and the cookie can then be read on that page.

Thanks for that advise “plintu”. It’s those little snippets of knowledge that separate the great from the good. :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service