/    Sign up×
Community /Pin to ProfileBookmark

PHP setcookie function

Hi, I’m trying to set a simple cookie using php, but it isn’t working for some reason. Just curious if anyone has an idea.

[code=php]$name = $_POST[‘firstname’].”_”.$_POST[‘lastname’];
setcookie (“name”, “$name”);[/code]

When I print the cookie it says the value is simply “_“. However, on the page that I set the cookie, I echo out $_POST[‘firstname’] and $_POST[‘lastname’] and it displays the names just fine.

Why isn’t the $_POST part getting written to the cookie?

to post a comment
PHP

14 Comments(s)

Copy linkTweet thisAlerts:
@trevzillaauthorApr 17.2008 — Oh, really quick, It doesn't seem to matter if I remove the quotes from $name. I still have the same problem.
Copy linkTweet thisAlerts:
@kurbyApr 18.2008 — what happens if you echo $name
Copy linkTweet thisAlerts:
@trevzillaauthorApr 18.2008 — Assuming I put "Trevor Olson" in the form on the page prior, when I echo $_POST['firstname']."_".$_POST['lastname']; that, it says "Trevor Olson." A.K.A. It echo's correctly, but it still doesn't write to the cookie correctly.
Copy linkTweet thisAlerts:
@NogDogApr 18.2008 — Just a sanity check here: setcookie() sends the applicable cookie HTTP header to the browser; but it does not set any value in the $_COOKIE array. You therefore will not see anything in $_COOKIE['firstname'] etc. until you access another page (or the same page again) from the same domain while the cookie has not yet expired.

Sorry if this is not the issue and you knew this already, but I've run into a number of occasions where people did not understand this, and thought that setcookie() would immediately set the value in the $_COOKIE array in the currently executing script.
Copy linkTweet thisAlerts:
@trevzillaauthorApr 18.2008 — Ah, thank you for the help, but I'm 'pretty' sure that is not my problem. I'll explain a little more clearly here just in case. (I not sure I entirely understood your comment)

I have three pages entirely. We'll call them 1, 2, and 3.

On page 1 I have a form that collects the firstname, lastname, and email. It then posts that info to page 2.

page 2 is where I run my echo commands. on page 2, it echos firstname and lastname and email correctly. I then try to setcookie() on page 2.

Then on page 3 it is supposed to access that cookie and read it out. But for some reason my setcookie on page 2 isn't working. Or at least it is not writing the correct value to it. It still creates the cookie though, just without the info from page 1.

Hope that makes sense.
Copy linkTweet thisAlerts:
@NogDogApr 18.2008 — Are you setting the cookie before [i]anything[/i] is output to the browser, including any text, spaces, newlines, etc. not within <?php ?> tags as well as echo/print commands? If not, the cookie will not be sent, as headers cannot be sent once any output is generated. Doing so should generate a warning. If you haven't already, you might want to turn on all error reporting while debugging, by adding the following lines to the top of the script:
[code=php]
<?php
ini_set('display_errors', 1); // later set to 0 for production version
error_reporting(E_ALL);
// . . . rest of script
?>
[/code]
Copy linkTweet thisAlerts:
@trevzillaauthorApr 18.2008 — Well. . .prior to this, no it was not before things were output to the browser. However, I read on w3 just before your reply, that my code had to be before <html> tags. So I moved the <php> script before those. Still no luck though.

Now, in your reply you say not within <php> tags?!? Seriously? I tried taking it out of the php tags, but it just displayed my code in the browser when I did this. Am I doing something wrong with that?

Just to clarify, here is the first 11 lines of my code, as of now.
[code=php]<?php ob_start();
$name = $_POST['firstname']." ".$_POST['lastname'];
$email = $_POST['email'];
echo "Your name is: ".$name;
echo "Your email is: ".$email;
setcookie ("name", $name, time() + 3600);
setcookie ("email", $email, time() + 3600);
setcookie ("photocookie", "", time() - 1);
setcookie ("photocookie1", "", time() - 1);

?>[/code]


the photocookies are deleting perfectley, the echos are working perfectly, but the name and email cookies aren't working at all! ?

I'll add that error thing right now, and get back to you as well. . .
Copy linkTweet thisAlerts:
@trevzillaauthorApr 18.2008 — Yeah, I get no error returns whatsoever. I'm so ridiculously stumped!
Copy linkTweet thisAlerts:
@NogDogApr 18.2008 — Sorry if I confused you. I meant that any output prior to the setcookie() would stop it from working, and "output" includes any text not contained within <?php ?> tags (including blank lines/spaces before the opening <?php tag).

I'd still recommend adding the debug code I suggested at the start of your script, as it may tell you things like if you're trying to use unset variables, etc. that might indicate where the problem is.

Another thing you need to look out for is domain confusion, such as accessing one page via "www.example.com" but another via "example.com", as they will not share cookies unless you adjust your PHP settings. You can avoid this by specifying the domain in the setcookie function, using the format ".example.com" (note the leading period).
[code=php]
setcookie("name", $name, time() + 3600, '/', '.example.com');
[/code]
Copy linkTweet thisAlerts:
@trevzillaauthorApr 18.2008 — Thank you again. . .

I did add the debug code, and I received no return on it whatsoever.

Also, I am doing my debugging in firefox, so after the cookie is 'supposed' to be set, I am just looking for it in tools->option->show cookies. It is not there. So for that reason I don't think the problem is with the domain. I'll keep playing with it though, but in the mean time, do you have any more ideas?
Copy linkTweet thisAlerts:
@NogDogApr 18.2008 — I can't think of any other "gotchas" at the moment. Here's a simple all-in-one script, if you want to play around with it to see if it provides any revelations for you.
[code=php]
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// set cookies from post data if received
if(!empty($_POST))
{
foreach($_POST as $key => $val)
{
setcookie($key, $val, time() + 3600);
}
}
// else update exiting cookies if set
elseif(!empty($_COOKIE))
{
foreach($_COOKIE as $key => $val)
{
setcookie($key, $val, time() + 3600);
}
}
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<p><a href="">Reload page</a></p>
<form action="" method="post">
<fieldset>
<legend>Test</legend>
<label>First name:
<input type="text" name="firstname" size="20" maxlength="20">
</label><br>
<label>Last name:
<input type="text" name="lastname" size="20" maxlength="20">
</label><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<pre>
Post Data:
<?php
if(!empty($_POST))
{
print_r($_POST);
}
?>

Cookie Data:
<?php
if(!empty($_COOKIE))
{
print_r($_COOKIE);
}
?>
</pre>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@NogDogApr 18.2008 — PS: Maybe try setting the cookie time to 0 (until browser is closed) in case it's a problem with clock settings either on the server or the client?
Copy linkTweet thisAlerts:
@trevzillaauthorApr 18.2008 — Well, thank you for all your help, alas, the php gods have decided to smite me and render my batch of cookies useless.

I've now tried your test page, and same thing. It posts fine, but no cookie is ever being displayed. I tried changing the expiration time to no avail.

I have another question. . .on a different .html page I set a cookie using javascript. In my plight to get this cookie to work, I tried using javascript in my .php file. Is that even allowed? (I don't think it is, but regardless, the javascript way didn't work either. I'm just wondering if I should continue to pursue the php method or if I should switch gears and try to fully pursue the javascript method?)
Copy linkTweet thisAlerts:
@trevzillaauthorApr 18.2008 — P.S. Here is the return that I got from your test page. . .

Post Data:

Array

(

[firstname] => Trevor

[lastname] => Olson

)

Cookie Data:

Array

(

[name] =>


)[/QUOTE]
×

Success!

Help @trevzilla spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...