Solved

Keeping form data if captcha isn't correct

Posted on 2011-02-21
9
403 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 110

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
Threat Trends for MSPs to Watch

See the findings.
Despite its humble beginnings, phishing has come a long way since those first crudely constructed emails. Today, phishing sites can appear and disappear in the length of a coffee break, and it takes more than a little know-how to keep your clients secure.

 
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 110

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 110

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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

734 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