Forums

setting a cookie on a form

tonyalferez 31 Dec, 2009
I'm trying to set a cookie with a form so that a user doesn't have to see the form if they've already filled it out. It's a simple form that just gathers their name and email address and then redirects them to another page. I inserted the following script at the top of the HTML code:
<?php
 
  if (!isset($_COOKIE['emailaddress'])) {
    header( "Location: http://www.treasurecycler.com/nwga/index.php?option=com_phocadownload&view=sections&Itemid=78" );
  }
  else {setcookie ("emailaddress", "set")}
 
    ?>

The result is that the page redirect happens even if it's the first time hitting the page. Its as if, the "header" command is being executed regardless of the "if" condition. Shouldn't it be checking to see if a cookie is set, then setting one, if not?

I've also tried to just set a cookie
<?php
setcookie ("emailaddress", "set")
?>

And no cookie is set.

I'm not a coder, just trying to figure this out on my own. If I need a php pro for this, I'll pay, but it seems simple enough for a novice to accomplish. Can anyone help?
GreyHead 31 Dec, 2009
Hi tonyalferez,

I think that the logic is faulty. The if redirects if the cookie is *not* set which is always true on a first visit so the cookie never gets set. Try without the !:
if ( isset($_COOKIE['emailaddress']) ) {

Bob
GreyHead 31 Dec, 2009
Hi tonyalferez,

That looks good.

I'd make one very small change to the redirect and use the Joomla code:
  global $mainframe;
  $mainframe->redirect('url_goes_here', 'message goes here');

Bob
tonyalferez 31 Dec, 2009
Didn't work for me...did you mean like this?

<?php

if (isset($_COOKIE['emailaddress'])) {
global $mainframe;
$mainframe->redirect('http://www.treasurecycler.com/nwga/index.php?option=com_phocadownload view=sections&Itemid=78', 'Tony's Test Message');
}
else setcookie ("emailaddress", "set")

?>

I get:

Parse error: syntax error, unexpected T_STRING in /home/treascyc/public_html/nwga/components/com_chronocontact/chronocontact.html.php(180) : eval()'d code on line 5
GreyHead 01 Jan, 2010
Hi Tonyalferez,

Yes, but you'd need to escape the ' in Tony's, or use an HTML entity instead.

'Tony\'s Test Message');
'Tony’s Test Message');

Bob
This topic is locked and no more replies can be posted.