Jump to content

Archived

This topic is now archived and is closed to further replies.

JSHINER

Cookie Question

Recommended Posts

Does anyone have a sample code I can look at that sets a cookie upon checking a box.

The form will have a text box asking for zip, and an option to remember zip. If it is checked, next time a visitor comes to the site they will go to:

www.site.com/index.php?action=search&zip=$zip.

I also need the form to send them to that specified search page, which it already does, but I also need it to set the cookie.

Any help / pointers would be greatly appreciated. I have never worked with cookies before.

Thank you!

Share this post


Link to post
Share on other sites
I haven't tested it, but it should work: [code]<?php
ob_start();
if(!empty($_POST['zip']))
{
echo "Your zip is {$_POST['zip']}";
if($_POST['remember_zip'])
{
echo "<br />We are remembering your zip code.";
setcookie("zip", $_POST['zip'], time()+3600*24*365); // store it for one year
}
}
else {
echo <<<EOF
<form action='{$_SERVER['REQUEST_URI']}' method='post'>
<label>Zip: <input type='text' name='zip' /></label><br />
<label><input type='checkbox' name='remember_zip' value='1' /> Remember zip code</label><br /><br />

<button type='submit'>Submit</button>
</form>

EOF;
}
ob_end_flush();
?>
[/code]

Note: The reason I can send headers (set a cookie in this example) is that I use output control.

Share this post


Link to post
Share on other sites
The current form:

<form action="search2.php?action=search" method="post">

Also, in action=search the zip code is validated, so could the cookie only be set if the else is true?

Share this post


Link to post
Share on other sites
I'm not sure what you mean, but just change [code]if($_POST['remember_zip'])[/code] to [code]if($_POST['remember_zip'] && *do validation stuff here*)[/code]

(You obviously need to do some validation where it says *do validation stuff here*)

Share this post


Link to post
Share on other sites
I need the form to post to the action=search. The validation is there.

Share this post


Link to post
Share on other sites
Just change the url in the action attribute on this line: [code]<form action='{$_SERVER['REQUEST_URI']}' method='post'>[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.