...

View Full Version : Can you include $_POST variables in setcookie()?



helraizer
11-19-2007, 05:50 PM
Hi all,

On my comments page, currently I have sessions to remember the username and email. This is good and works well but not from once the user closes the window. I was thinking of using cookies to save it these pieces of data instead. So that it can be loaded each time (until the cookie expires).

I know that you can use variables such as:



<?php

$variable = "my cookie value - username";

setcookie("user", $variable, time()+3600*24, "/");

?>


So that the cookie value is that of $variable and will expire in 24hours.

Is it possible to save the $_POST variables of the username and email in the cookie? So far, everything (input form and then the comments) is on one page, or would it be doable if it were on two pages? So it'd be like:




<?php

$usrnme = $_POST['username'];

setcookie("user", $usrnme, time()+3600*24, "/");



Hope that makes sense,

Thanks,
Sam

Fumigator
11-19-2007, 05:56 PM
Sure. But you could have just tried it, ya know.

JordanW
11-19-2007, 05:57 PM
What you have there:



<?php
$usrnme = $_POST['username'];
setcookie("user", $usrnme, time()+3600*24, "/");
?>



Should work perfectly!


~Jordan

helraizer
11-19-2007, 06:29 PM
It does not seem to actually set the cookie, for some reason. Any ideas?

Also, doesn't the setcookie function have to go before the <html> tags? Which means that the cookie is sent before the $_POST variables are set, surely? Or have I got that part completely wrong? :p

Sam

Inigoesdr
11-19-2007, 07:00 PM
The post variables are set before your file is parsed.

helraizer
11-19-2007, 07:10 PM
The post variables are set before your file is parsed.

In theory yes, but since I have everything on one page (including the form to be posted), until the form is submitted there are no values assigned to the variables. Is that where my problem lies, do you think?

Sam

CFMaBiSmAd
11-19-2007, 07:24 PM
For your current code, check your web server log for errors and/or turn on full php error reporting (when learning, developing code, or debugging code, you should always use full php error reporting to get php to help you.) You will probably find that it is notifying you that the code is referencing undefined variables, because they have not been set yet. (Setting a cookie with an empty value actually deletes the cookie if I remember correctly.)

Your code should only reference any $_POST variables after the form has been submitted, using conditional logic. If we assume that your form has a submit button with name="submit" -

if(isset($_POST['submit']))
{
// code to process the form
// only reference $_POST variables when the form has been submitted
$usrnme = $_POST['username'];
...
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum