Solved

Keeping form data if captcha isn't correct

Posted on 2011-02-21
9
397 Views
Last Modified: 2012-05-11
I have this form on a website and it works great if the CAPTCHA is filled in correctly. How can I make it remember the form fields if the person enters the captcha wrong so they don't have to reenter.

The page checks the captcha, submits form, saves it to database and emails the admin and the user.
<?php
session_start();

//Database Information
CONNECTION INFORMATION
//Connect to database

$link = mysql_connect ( $dbhost, $dbuser, $dbpass);

if (!is_resource($link))
{
      die("Could not connect: " . mysql_error());
}

mysql_select_db($dbname) or die(mysql_error());
if(isset($_POST["captcha"]))
if($_SESSION["captcha"]==$_POST["captcha"])
{

$successful_entry = 0;

if (isset($_POST['action']))
{
      if ($_POST['action'] == "update")
      {
          try {
            $FirstName = $_POST['FirstName'];
            mysql_real_escape_string($FirstName, $link);

            $LastName = $_POST['LastName'];
            mysql_real_escape_string($LastName, $link);

            $SubmitEmail = $_POST['SubmitEmail'];
            mysql_real_escape_string($SubmitEmail, $link);
            
          $weddingdate = $_POST['weddingdate'];
            $weddingdate = mysql_real_escape_string($weddingdate, $link);
            
            $weddingdate = str_replace("-", "/", $weddingdate);
            $weddingdate_ts = strtotime($weddingdate);
            $weddingdate = date("Y-m-d", $weddingdate_ts);
            
            $phone_01 = $_POST['phone_01'];
            mysql_real_escape_string($phone_01, $link);

            $Password = $_POST['Passwword'];
            mysql_real_escape_string($Password, $link);

            $rs = mysql_query("select * from RealWedding where brideemail = '".$SubmitEmail."'");
            if (mysql_affected_rows() > 0)                  
            {          
                    throw new Exception("<b>I'm sorry, this email address is already in use. Please use another email or <br><a href=\"login.php\">Login Here</a> to access your information.</b>");
            }           
             
                  
            $currenttime = date('Y-m-d H:i:s');

            $sql = "INSERT INTO RealWedding (FirstName, LastName, phone_01, brideemail, Password, weddingdate, DateAdded, DateUpdated) VALUES ('$FirstName', '$LastName', '$phone_01', '$SubmitEmail', '$Password', '$weddingdate', '$currenttime', '$currenttime')";
      
            $insert_result = mysql_query($sql);

            if (!($insert_result))
            {
                  echo mysql_error();
                  echo "<br>\n";
                  echo "$sql<br>\n";
                  exit;
            }
      $food_service_worker_id = mysql_insert_id();      



            // Send e-mail to admin
            $config_sql = "SELECT * FROM Config WHERE Name='JoinSubmitEmailAddress'";
            $config_sql_result = mysql_query($config_sql);
            
            if (mysql_num_rows($config_sql_result))
            {
                  $config_row = mysql_fetch_assoc($config_sql_result);
                  $mail_To = $config_row['Value'];
                  
                  $mail_From = "From: " . $config_row['Value'];
                  $mail_Subject = "Someone New Has Joined Black Hills Bride";
                  
                  $config_sql = "SELECT * FROM Config WHERE Name='JoinEmailSubmitted'";
                  $config_sql_result = mysql_query($config_sql);
                  if(!$config_sql_result) die(mysql_error());
                  $config_row = mysql_fetch_assoc($config_sql_result);
                  if(!$config_row) die('Configuration for JoinEmailSubmitted not found');
                   

                  $message = 'Config: '.$config_row['Value'];

                  $formdata = '';
                  foreach($_POST as $key=>$value) 
                   $formdata.=$key.':'.$value."\n";
                  $message = $config_row['Value']."\n\n".$formdata;


                  mail($mail_To, $mail_Subject, $message . "\n\n", $mail_From);
            }
            else
            {
                  echo "Error retrieving admin e-mail address from database\n";
                  exit;
            }
			
			 // Send e-mail to Person Joining
            $config_sql = "SELECT * FROM Config WHERE Name='JoinSubmitEmailAddress'";
            $config_sql_result = mysql_query($config_sql);
            
            if (mysql_num_rows($config_sql_result))
            {
                  $config_row = mysql_fetch_assoc($config_sql_result);
                  $mail_To = $SubmitEmail;
                  
                  $mail_From = "From: " . $config_row['Value'];
                  $mail_Subject = "Thank You For Joining Black Hills Bride";
                  
                  $config_sql = "SELECT * FROM Config WHERE Name='JoinThankYou'";
                  $config_sql_result = mysql_query($config_sql);
                  if(!$config_sql_result) die(mysql_error());
                  $config_row = mysql_fetch_assoc($config_sql_result);
                  if(!$config_row) die('Configuration for JoinEmailSubmitted not found');
                   

                  $message = 'Config: '.$config_row['Value'];

                  $formdata = '';
                  foreach($_POST as $key=>$value) 
                   $formdata.=$key.': '.$value."\n";
                  $message = $config_row['Value']."\n\n".$formdata;


                  mail($mail_To, $mail_Subject, $message . "\n\n", $mail_From);
            }
            else
            {
                  echo "Error retrieving admin e-mail address from database\n";
                  exit;
            }
            
            
            $successful_entry = 1;

            session_register("myusername");
            session_register("mypassword"); 

            $_SESSION['username'] = $SubmitEmail;
            $_SESSION['userid'] = $food_service_worker_id;

            # header("location:login_success.php");
            header("location:view_listing.php?id=" . $food_service_worker_id);
      } 
         catch(Exception $ex)
         {
            $errormsg = $ex->getMessage();
         }      
        

      }
}

}
else
{
	$errormsg = '<b>Your CAPTCHA CODE DID NOT MATCH. PLEASE REENTER</b>';
}


?>

    
     <?php
     
      
      if ($successful_entry)
      {
            echo "<font class=style6>Thank you for joining Black Hills Bride. An email confirmation will be sent to you shortly. <a href=\"login.php\">Login</a> to add or edit your wedding or engagement listing.</font> ";
      }
      else
      {
            echo "<form action=\"join.php\" enctype=\"multipart/form-data\" method=\"post\" name=\"update_form\">\n";
            echo "<input type=\"hidden\" name=\"action\" value=\"update\" />\n";
      
            echo "<table width=\"412px\" border=\"2\" bordercolor=\"#CCCCCC\"><tr><td>\n";
            echo "<table width=\"410px\" bgcolor=\"#FFFFFF\">\n";

 			echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\" colspan=\"2\">\n";
                   echo "</td>\n";
            echo "</tr>\n";

            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\" colspan=\"2\">\n";
            echo "<font class=\"style7\"><b>Your Information:</b></font>\n";
            echo "</td>\n";
            echo "</tr>\n";
            
            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\">\n";
            echo "First Name:\n";
            echo "</td>\n";
            echo "<td align=\"left\">\n";
            echo "<input type=\"text\" name=\"FirstName\" value=\"$FirstName\" size=\"30\" />\n";
            echo "</td></tr>\n";      
            
            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\">\n";
            echo "Last Name:\n";
            echo "</td>\n";
            echo "<td align=\"left\">\n";
            echo "<input type=\"text\" name=\"LastName\" value=\"$LastName\" size=\"30\" />\n";
            echo "</td></tr>\n";
            
            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\">\n";
            echo "Wedding Date: (mm/dd/yyyy)\n";
            echo "</td>\n";
            echo "<td align=\"left\">\n";
            echo " <input type=\"text\" name=\"weddingdate\" value=\"$weddingdate\"/>
                      <a href=\"#\" onclick=\"cal.select(document.forms['update_form'].weddingdate, 'anchor1', 'MM/dd/yyyy'); return false;\" name=\"anchor1\" id=\"anchor1\"><img src=\"images/b_calendar.png\" border=\"0\" /></a>\n";
            echo "</td></tr>\n";
            
            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\">\n";
            echo "Email: (this will be your username)\n";
            echo "</td>\n";
            echo "<td align=\"left\">\n";
            echo "<input type=\"text\" name=\"SubmitEmail\" value=\"$SubmitEmail\" size=\"30\" />\n";
            echo "</td>\n";
            echo "</tr>\n";
                  
            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\">\n";
            echo "Phone:\n";
            echo "</td>\n";
            echo "<td align=\"left\">\n";
            echo "<input type=\"text\" name=\"phone_01\" value=\"$phone_01\" size=\"30\" />\n";
            echo "</td>\n";
            echo "</tr>\n";
            
            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\">\n";
            echo "Password:\n";
            echo "</td>\n";
            echo "<td align=\"left\">\n";
            echo "<input type=\"text\" name=\"Passwword\" value=\"$Password\" size=\"30\" />\n";
            echo "</td>\n";
            echo "</tr>\n";
			
		echo "<tr><td align=\"center\" colspan=\"2\">\n";  if ($errormsg)
      {
                  echo "<font style='color:red'>$errormsg</font> <br>";
      }
	  echo"CAPTCHA:
	(antispam code, <b><font color=\"#000000\">Enter ONLY the 3 Black Symbols)</font></b><br>
	<table><tr><td><img src=\"captcha.php\" alt=\"captcha image\"></td><td><input type=\"text\" name=\"captcha\" size=\"3\" maxlength=\"3\"></td></tr></table>
</td></tr>\n";
			
			
            echo "<tr class=\"style6\">\n";
            echo "<td align=\"left\">\n";
            echo "<input type=\"submit\" value=\"Submit Now\" name=\"Submit\" id=\"Submit\" />\n";
            echo "</td>\n";
            echo "</tr>\n";
      
      
            echo "</table>\n";
            echo "</td></tr></table>\n";
            echo "</form>\n";
            
            
      }
?>

Open in new window

0
Comment
Question by:katlees
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 16

Expert Comment

by:Chris Harte
ID: 34943852
Use session variables.

So, on line 27 you would use

$_SESSION['FirstName'] = $_POST['FirstName'];

instead of
$FirstName = $_POST['FirstName'];
0
 
LVL 11

Expert Comment

by:level9wizard
ID: 34943929
You'll also need to then print that session inside your form. So for example

<input type="text" name="FirstName" value="<?php if(isset($_SESSION['FirstName'])) echo $_SESSION['FirstName'];?>" />

By the way, you're missing an important step in your effort for MySQL security.
You have:
mysql_real_escape_string($LastName, $link);
But what you want is:
$LastName = mysql_real_escape_string($LastName, $link);
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 34944073
This is a great question.  The example here shows how it is done.  It uses the session, but could just as well use the data base.
http://www.laprbass.com/RAY_remember_form_data.php
<?php // RAY_remember_form_data.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO REMEMBER FORM DATA FROM ONE FORM SUBMISSION TO THE NEXT


// USE THE SESSION ARRAY TO STORE THE FORM VALUES
session_start();

// INITIAL TRIP INTO THE SCRIPT
if (!isset($_SESSION["formname"]))
{
    // INITIALIZE THE VALUES FOR USE IN THE FORM LATER
    $_SESSION["formname"] = '';
    $_SESSION["formmail"] = '';
}

// TEST TO SEE IF THE FORM HAS BEEN POSTED
if (!empty($_POST))
{
    // COPY THE POST VALUES INTO THE SESSION
    $_SESSION["formname"] = $_POST["formname"];
    $_SESSION["formmail"] = $_POST["formmail"];

    // ACKNOWLEDGE THE POST (TEST CAPTCHA HERE, MAYBE?)
    echo "THANK YOU, " . htmlentities($_POST["formname"]);
    echo "<br/>";

    // OTHER PROCESSING AS NEEDED
    // die("ALL DONE");
}

// CREATE THE FORM USING HEREDOC SYNTAX
$form = <<<FORM
<form method="post">
NAME: <input name="formname" value="{$_SESSION["formname"]}" />
MAIL: <input name="formmail" value="{$_SESSION["formmail"]}" />
<input type="submit" />
</form>
FORM;

echo $form;

Open in new window

0
 
LVL 3

Accepted Solution

by:
Outliver earned 250 total points
ID: 34944109
simply replace $FirstName with {$_POST['FirstName']} on 205 and so on.

But here's a hint: Your script may ruin your html if the user enters ">" for example.
It's always a good idea to escape that. Have a look htmlentities and htmlspecialchars.

Greetings
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:katlees
ID: 34944192
MunterMan and Level 9. I tried yours and it didn't work. Values don't save... Ray - I'll attempt yours now
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34944439
Just click the link I posted and you can see the demonstration of the script I posted.  I hope it makes sense to you.  You need to be aware that your clients MUST be accepting cookies for the session-based strategy to work.  Otherwise you would have a more complicated issue to deal with.

Please post back with any questions.
0
 

Author Closing Comment

by:katlees
ID: 34944658
Outliver - yours worked slick and was easy. Ray, I did yours on it's own and it worked great so I split points as you posted first. It was just too much editing on the form I already had.
0
 
LVL 11

Expert Comment

by:level9wizard
ID: 34944674
katlees,

I don't care about the points - did you notice my comments on mysql_real_escape_string() ?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34944717
Agree with level9wizard about mysql_real_escape_string() -- that might be the most important part of the advice here.
Agree with Outliver - always Filter Input and Escape Output.

Best to all, ~Ray
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ransomware continues to be a growing problem for both personal and business users alike and Antivirus companies are still struggling to find a reliable way to protect you from this dangerous threat.
Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now