Solved

Keeping form data if captcha isn't correct

Posted on 2011-02-21
9
398 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 17

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 109

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
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 
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
 

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 109

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 109

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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Joomla 2.5 shopping cart 7 23
Showing random records from database 10 37
How can I make this form submit to itself? 10 27
How do I fix this UPDATE error? 7 22
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
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)

770 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