Link to home
Start Free TrialLog in
Avatar of Bulg
BulgFlag for United States of America

asked on

How to set a cookie in registration form?

hello experts I am trying to set cookies in my registration form the thing is.. after submitting the form it goes to a 2nd page if lets say the captcha is wrong the 2nd page sends the user back to a 3rd page what is exactly like the 1st registration page but it has an error showing what was wrong and the form didnt submit. i am trying to make a cookie that keeps the information inputed from the 1st registration form the the 3rd file  thx for the help if u need code plz ask thx
Avatar of robofix
robofix

Dear Bulg,
I use cookies myself on a regular basis for websites.
I found the following guidance very helpful and concise:
http://www.w3schools.com/PHP/php_cookies.asp

Use the session, not the cookie.  

Just do session_start() at the top of every page.  Then place your data elements into the $_SESSION array, like this:

$_SESSION['foo'] = "BAR";

The $_SESSION array will be available in all variable scopes and in all scripts that use session_start() at the top. This is going to be a lot easier than learning about how to use cookies, trust me!!

Best, ~Ray
To do this make sure that session_start() is at the top of every page.  That is typically the first problem encountered by beginners.

The concept of using three pages is rather odd.  If I could suggest an alternate idea (assuming using a templating engine is out and you want to use simple pages)?  I would start with the form page as a separate HTML page (no PHP business logic other than form variables being posted back into the form, etc).  Your PHP page could then be coded with a simple if { } else { } construct.  if the form was posted and the session variable matches process the form and show a thank you page (again another simple HTML page) otherwise show the original HTML form page, but show the error message (This could be done with a simple empty variable that is initialized in the PHP file.  This would get changed if the form is not valid).
#PHP FILE
<?php
$message = '';
$finished = false;
if( isset($_POST['submit']) ) {
    if($_SESSION['captcha'] == $_POST['captcha']) {
        # Do whatever form processing needed here
        $finished = true;
    } else {
        $message = 'Sorry the captcha you entered was not valid';
    }
}
# If this is false the form was either not posted or an error occurred.
if($finished == false) {
    require_once('form.html');
} else {
    require_once('processed.html');
}
?>
 
HTML>>>
<div>
    <?php
    # This will only have a value if the captcha is wrong.
    echo $message;
    ?>
</div>
<form>
    First Name: <input type='text' name='first_name' />
    Last Name: <input type='text' name='last_name' />
    Captcha: <input type='text' name='captcha' />
    <input type='submit' name='submit' />
</form>
<<<HTML

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I swear I need to learn how to type faster.
Avatar of Bulg

ASKER

yea i was looking at that before i posted the question but i dont seem to understand it very well. Like this example alex porter is the actual saved name for "user" but how do i make 'user'=the input of nickname in my form
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
###################
//ok this is one my fields
<input name="nickname" type="text" id="nickname" tabindex="30" onChange="toggle_nickname(this.id)" /><span id="nickname_exists"></span>
 
//how do i set the cookie for that field?
<?php
setcookie("user", "nickname", time()+3600);
?>
//and later on 
echo $_COOKIE["user"]; 
//will display the nickname that was put in the field nickname ?

Open in new window

Are you trying to use cookies to store information for retrieval later (as in the client closes their browser and returns tomorrow)?  If not than sessions are a lot easier to work with as Ray said.
Avatar of Bulg

ASKER

i actually have a session_start(); already but its for the actual log in of the users.
ok let me see if i get this right how would it look like exactly here is my code.
btw u guys are FAST in the time i type my comment you 2 ware racing for 2nd answer :P
<?php
session_start();
?>
<form action="../registration/reg_welcome.php" method="post" enctype="application/x-www-form-urlencoded" name="form1" id="form1">
    <input type="hidden" name="recipient" /> 
    <input type="hidden" name="redirect" value= />  
    <div class="input">
      <h3>First Name</h3>
      <p><span id="sprytextfield1">
        <input name="firstname" type="text" class="np1" id="firstname" tabindex="10" />
        <span class="textfieldRequiredMsg">First name is required.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span></p>
      </div><br/>
<?php
$_SESSION["registrationData"] = array(
   "firstName" => $_POST["firstName"],
);
?>
 
// and in the other page i can input
<?php
session_start();
?>
<input name="firstname" value="<?php echo $_POST["firstName"];?>" type="text" class="np1" id="firstname" tabindex="10" />
//something like that correct me if i am wrong :D thx for the fast answers 

Open in new window

@Bulg: If I have suggested this before, please forgive me for repeating myself.  You need to get some foundation in the basics of PHP.  It is hard to learn a language by asking questions about it one-at-a-time.  Consider buying this book and working through the numerous excellent examples (including EXACTLY this question):
http://www.sitepoint.com/books/phpmysql4/

When you are working with login forms and cookies, a comment like line 12 // and later on evinces a misunderstanding of the HTTP protocol and the way servers, browsers and cookies work together.

If you buy that book, you will get the information you need, but maybe this code snippet will give you something you can test with to see what is happening with setcookie() and the $_COOKIE array.  Please read the code and comments carefully - this is not simple, so do not become frustrated if it is not immediately clear to you - just keep stepping through it and eventually the lightbulb will come on.

HTH, ~Ray
<?php // RAY_cookie_example.php
 
// RECEIVE FORM INPUT AND SET A COOKIE WITH THE NAME AND VALUES FROM THE FORM
// MAN PAGE: http://us.php.net/manual/en/function.setcookie.php
// TO SEE COOKIES IN FIREFOX, FOLLOW TOOLS => OPTIONS => PRIVACY => SHOW COOKIES
 
define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )
 
if (!empty($_POST)) // IF THE FORM HAS BEEN POSTED
{
 
// TIDY UP THE POST INPUT - CLEAN AND NOT MORE THAN 16 BYTES
   $name = substr(clean_string($_POST["name"]),0,16);
   $data = substr(clean_string($_POST["data"]),0,16);
 
// BE SURE WE HAVE USEFUL INFORMATION
   if ( ($name == '') || ($data == '') ) die("MISSING INPUT: PLEASE <a href=\"$PHP_SELF\">TRY AGAIN</a>");
 
 
// CHOOSE THE COOKIE NAME AND VALUE
   $cookie_name    = $name;
   $cookie_value   = $data;
 
 
 
// ESTABLISH THE COOKIE LIFE - CHOOSE ONE OF THESE FOR THE COOKIE
// USE THIS TO MAKE COOKIE EXPIRE AT END OF BROWSER LIFE
   $cookie_expires = 0;
 
// USE THIS TO MAKE A PERSISTENT COOKIE - DEFINE COOKIE_LIFE IN SECONDS - date('Z') IS UTC OFFSET IN SECONDS
   $cookie_expires = time() + date('Z') + 30 * 60 * 60 * 24;
 
 
 
// ESTABLISH THE COOKIE DOMAIN SCOPE - CHOOSE ONE OF THESE FOR THE COOKIE
// MAKE THE COOKIE AVAILABLE TO ALL DIRECTORY PATHS IN THE WWW ROOT
   $cookie_path	= '/';
 
// MAKE THE COOKIE AVAILABLE TO ALL SUBDOMAINS - DOMAIN NAME STARTS WITH DOT AND OMITS WWW (OR OTHER SUBDOMAINS).
   $x = explode('.', strtolower($_SERVER["HTTP_HOST"]));
   $y = count($x);
   if ($y == 1) // MAYBE 'localhost'?
   {
      $cookie_domain = $x[0];
   } else // SOMETHING LIKE 'www2.atf70.whitehouse.gov'?
   {
// USE THE LAST TWO POSITIONS TO MAKE THE HOST DOMAIN
      $cookie_domain = '.' . $x[$y-2] . '.' . $x[$y-1];
   }
 
 
 
// MAKE THE COOKIE AVAILABLE TO HTTP, NOT JUST HTTPS
   $cookie_secure    = FALSE;
 
 
 
// HIDE COOKIE FROM JAVASCRIPT (PHP 5.2+)
   $cookie_http      = TRUE;
 
 
 
// SET THE COOKIE
   if (setcookie($cookie_name, $cookie_value, $cookie_expires, $cookie_path, $cookie_domain, $cookie_secure, $cookie_http))
   {
      echo "<br/>SUCCESS!  THE COOKIE HAS BEEN SET AND WILL BE AVAILABLE TO THE NEXT PAGE LOAD \n";
   }
   else
   {
      echo "<br/>FAILURE!  THE COOKIE WAS NOT SET AS EXPECTED \n";
   }
 
 
 
// AT THIS POINT, THE COOKIE HAS BEEN SET, BUT IT IS _NOT_ AVAILABLE TO THIS SCRIPT.  IT WILL BE AVAILABLE TO THE NEXT SCRIPT!
// OR WE CAN EXPLICITLY ADD INFORMATION TO $_COOKIE IF WE NEED TO
   echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";
   echo '<pre>$_POST CONTAINS ';   var_dump($_POST);   echo "</pre>\n";
   echo "<br/>THE COOKIE HAS BEEN SET WITH THESE VALUES: \n";
   echo "<br/>COOKIE NAME: $cookie_name \n";
   echo "<br/>COOKIE VALUE: $cookie_value \n";
   echo "<br/>COOKIE EXPIRES: $cookie_expires ";
   echo " == " . date('r') . "\n";
   echo "<br/>COOKIE PATH: $cookie_path \n";
   echo "<br/>COOKIE DOMAIN: $cookie_domain \n";
   echo "<br/>COOKIE SECURE: "; var_dump($cookie_secure); echo " \n";
   echo "<br/>COOKIE HTTP: ";   var_dump($cookie_http);   echo " \n";
 
   echo "<br/>";
   echo "<br/>TO SEE THE COOKIES, IF ANY, <a href=\"$PHP_SELF\">CLICK HERE</a> \n";
   echo "<br/>";
}
 
// END OF SETTING THE COOKIE
?>
 
 
<form method="post">
COOKIE NAME: <input name="name" /><br/>
COOKIE DATA: <input name="data" /><br/>
<input type="submit" />
</form>
 
 
<?php
// SHOW THE COOKIE ARRAY, IF ANY
echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";
 
 
 
// A FUNCTION TO FORCE A STRING TO CHARACTERS ONLY
function clean_string($string)
{
   return trim(ereg_replace('[^a-zA-Z0-9_]', '', $string));
}
?>

Open in new window

Almost - the trick is the order of events. The:

<?php
$_SESSION["registrationData"] = array(
   "firstName" => $_POST["firstName"],
);
?>

should go on the second page, when you are trying to process the data that the user submitted to you.

On the third page, you've almost got iit, except you're using POST instead of SESSION:

value="<?php echo $_POST["firstName"];?>"

should be

value="<?php echo $_SESSION["firstName"];?>"  
Avatar of Bulg

ASKER

thx for the link Ray_Paseur i will make sure to check that book out. I do have to learn what i am doing and looking forward on it.
Is this right gr8gonzo?

//first lines of code on the page in reg_welcome where the form is being submitted
<?php session_start();
?>
<?php
$_SESSION["registrationData"] = array(
   "firstname" => $_POST["firstname"],
);
?>
###########
//and this is the field in my 3rd page i tested it out but nothing is displaying in the firstname field
<input name="firstname" type="text" class="np1" id="firstname" tabindex="10" value="<?php echo $_SESSION["firstname"];?>"/>

Open in new window

@Bulg: We can only be guessing about whether or not that is right - small code segments are VERY RISKY ways to get advice when you have so many moving parts.  May be better to post the entire scripts so we can really see what the code is doing!
Avatar of Bulg

ASKER

sure thing. thought it will be easier to read :P
<?php session_start();
?>
<?php
$_SESSION["registrationData"] = array(
   "firstname" => $_POST["firstname"],
);
?>
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
 
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
header( "Location: ");
 
}//captcha check script
?>
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/login/config.php';
 
// table name
$tbl_name=temp_members_db;
$salt = ".,1X7&42(0$as@Vz)-=@xVs4BG.$(@_$8a1(23]};:";
// Random confirmation code
$confirm_code=md5(uniqid(rand()));
									 
  $firstname=mysql_real_escape_string($_POST['firstname']);
  $lastname=mysql_real_escape_string($_POST['lastname']);
  $email=mysql_real_escape_string($_POST['email']);
  $nickname=mysql_real_escape_string($_POST['nickname']);
  $password=mysql_real_escape_string (md5($_POST['password'].$salt));
  $birthdate=mysql_real_escape_string($_POST['birthdate']);
  $birthdate1=mysql_real_escape_string($_POST['birthdate1']);
  $birthdate2=mysql_real_escape_string($_POST['birthdate2']);
  $country=mysql_real_escape_string($_POST['country']);										
  $termscheck=mysql_real_escape_string($_POST['termscheck']);
	// sends all data from this fields into database				  
$sql= "INSERT INTO $tbl_name(`confirm_code`,`firstname`, `lastname`,`email`,`nickname`,`password`,`birthdate`,`birthdate1`,`birthdate2`,`country`,`termscheck` ) values ('$confirm_code','$firstname','$lastname','$email','$nickname','$password','$birthdate','$birthdate1','$birthdate2','$country','$termscheck')";
$result=mysql_query($sql);
  die('The code you entered was incorrect.  Go back and try again.');
// if suceesfully inserted data into database, send confirmation link to email
if($result){
 
// ---------------- SEND MAIL FORM ----------------
 
// send e-mail to ...
$to=$email;
 
// Your subject
$subject="";
 
// From
$header="from: ";
 
// Your message
$message="This is you confirmation link. \r\n";
$message.=" \r\n";
$message.="";
 
// send email
$sentmail = mail($to,$subject,$message,$header);
 
}
 
// if not found
else {
echo "Not found your email in our database";
}
 
// if your email succesfully sent
if($sentmail){
header( "Location: ");
echo "Your Confirmation link Has Been Sent To Your Email Address.";	
}
else {
echo "Cannot send Confirmation link to your e-mail address";
}
?>
#################################
<?php
session_start();
?>
  <form action="../registration/reg_welcome.php" method="post" enctype="application/x-www-form-urlencoded" name="form1" id="form1">
    <input type="hidden" name="recipient" /> 
    <input type="hidden" name="redirect" value= />  
    <div class="input">
      <h3>First Name</h3>
      <p><span id="sprytextfield1">
    <input name="firstname" type="text" class="np1" id="firstname" tabindex="10" value="<?php echo $_SESSION["firstname"];?>"/>
        <span class="textfieldRequiredMsg">First name is required.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span></p>
      </div>
<label for="submit"></label>
      <input type="submit" name="submit" id="submit" value="" tabindex="125" />
      </p>  <br />
    </form>
//the rest of this page is just other fields and css hope it helps

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bulg

ASKER

for some reason its not working anyway i can find why?
We'll need more information than "it's not working" - can you provide a little more detail on what exactly it IS doing right now?

Also, on line 39, I see this:

  die('The code you entered was incorrect.  Go back and try again.');

But there's no logic around it, so it looks like it will always be executed and will cause the page to stop at that point with that message being shown.
Avatar of Bulg

ASKER

sorry i mean its redirecting to the page that it should file3 but its not displaying anything in the firstname field also the line 39 its suppose to be at line 14 right after the header;
it kills the rest of the script when ever the captcha fails so db wont get the unneeded info
Thank you, but did you get it working?