PHP SecurImage CAPTCHA Validation and Form Submit On One Page

I am trying to incorporate CAPTCHA using securimage within php pages where my form has an action that submits entered data to a URL so that it can be added to a CRM.  The form works perfectly before trying to add the CAPTCHA although I am having trouble adding it in.

I want to use one PHP page to incorporate the form, validation of entered CAPTCHA, messages if CAPTCHA entered incorrectly, and a submit to a URL if successful.  Here is what I am using to try to make this happen.

http://www.phpcaptcha.org/documentation/quickstart-guide/

Please give me an example of a php page that would allow me to do all of the above.

Thank you.

Robin
rporter45Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
0
rporter45Author Commented:
I have read that.  Thank you.  Does not help with securimage though.  Thanks anyway.
0
Dave BaldwinFixer of ProblemsCommented:
What error message are you getting?  This page describes problem areas: http://www.phpcaptcha.org/documentation/debugging-problems/
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

rporter45Author Commented:
Please confirm how to alter this code so that instead of sending an email with form data once validation of captcha is correct, it submits to a URL instead using a form action.

<?php
session_start();

// this MUST be called prior to any output including whitespaces and line breaks!

$GLOBALS['DEBUG_MODE'] = 1;


// CHANGE TO 0 TO TURN OFF DEBUG MODE


// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT

$GLOBALS['ct_recipient']   = 'YOU@EXAMPLE.COM';

// Change to your email address!
$GLOBALS['ct_msg_subject'] = 'Securimage Test Contact Form';

?>
<!DOCTYPE html PUBLIC "-

//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">


<head>
 

<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
 

<title>Securimage Example Form</title>
 

<style type="text/css">
  <!--
  .error { color: #f00; font-weight: bold; font-size: 1.2em; }
  .success { color: #00f; font-weight: bold; font-size: 1.2em; }
  fieldset { width: 90%; }
  legend { font-size: 24px; }
  .note { font-size: 18px;
  -->
  </style>


</head>


<body>



<fieldset>
<legend>Example Form</legend>



<p class="note">
  This is an example PHP form that processes user information, checks for errors, and validates the captcha code.<br />
  This example form also demonstrates how to submit a form to itself to display error messages.
</p>

<?php

process_si_contact_form();

// Process the form, if it was submitted

if (isset($_SESSION['ctform']['error']) &&  $_SESSION['ctform']['error'] == true): /* The last form submission had 1 or more errors */ ?>
<span class="error">There was a problem with your submission.  Errors are displayed below in red.</span><br /><br />
<?php elseif (isset($_SESSION['ctform']['success']) && $_SESSION['ctform']['success'] == true): /* form was processed successfully */ ?>


<span class="success">The captcha was correct and the message has been sent!</span><br /><br />
<?php endif; ?>



<form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']) ?>" id="contact_form">
 

<input type="hidden" name="do" value="contact" />

  <p>
    <strong>Name*:</strong>&nbsp; &nbsp;<?php echo @$_SESSION['ctform']['name_error'] ?><br />
   

<input type="text" name="ct_name" size="35" value="<?php echo htmlspecialchars(@$_SESSION['ctform']['ct_name']) ?>" />
  </p>

  <p>
    <strong>Email*:</strong>&nbsp; &nbsp;<?php echo @$_SESSION['ctform']['email_error'] ?><br />
   

<input type="text" name="ct_email" size="35" value="<?php echo htmlspecialchars(@$_SESSION['ctform']['ct_email']) ?>" />
  </p>

  <p>
    <strong>URL:</strong>&nbsp; &nbsp;<?php echo @$_SESSION['ctform']['URL_error'] ?><br />
   

<input type="text" name="ct_URL" size="35" value="<?php echo htmlspecialchars(@$_SESSION['ctform']['ct_URL']) ?>" />
  </p>

  <p>
    <strong>Message*:</strong>&nbsp; &nbsp;<?php echo @$_SESSION['ctform']['message_error'] ?><br />
   

<textarea name="ct_message" rows="12" cols="60"><?php echo htmlspecialchars(@$_SESSION['ctform']['ct_message']) ?></textarea>
 

</p>

  <p>
   

<img id="siimage" style="border: 1px solid #000; margin-right: 15px" src="./securimage_show.php?sid=<?php echo md5(uniqid()) ?>" alt="CAPTCHA Image" align="left" />
    <object type="application/x-shockwave-flash" data="./securimage_play.swf?bgcol=#ffffff&amp;icon_file=./images/audio_icon.png&amp;audio_file=./securimage_play.php" height="32" width="32">
    <param name="movie" value="./securimage_play.swf?bgcol=#ffffff&amp;icon_file=./images/audio_icon.png&amp;audio_file=./securimage_play.php" />
    </object>
    &nbsp;
    <a tabindex="-1" style="border-style: none;" href="#" title="Refresh Image" onclick="document.getElementById('siimage').src = './securimage_show.php?sid=' + Math.random(); this.blur(); return false"><img src="./images/refresh.png" alt="Reload Image" height="32" width="32" onclick="this.blur()" align="bottom" border="0" /></a><br />
    <strong>Enter Code*:</strong><br />
     <?php echo @$_SESSION['ctform']['captcha_error'] ?>
   

<input type="text" name="ct_captcha" size="12" maxlength="16" />
  </p>

  <p>
    <br />
   

<input type="submit" value="Submit Message" />
  </p>

</form>
</fieldset>

</body>
</html>

<?php



// The form processor PHP code
function process_si_contact_form()
{
  $_SESSION['ctform'] = array();

// re-initialize the form session data

  if ($_SERVER['REQUEST_METHOD'] == 'POST' && @$_POST['do'] == 'contact') {
        

// if the form has been submitted

    foreach($_POST as $key => $value) {
      if (!is_array($key)) {
            

// sanitize the input data
        if ($key != 'ct_message') $value = strip_tags($value);
        $_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
      }
    }

    $name    = @$_POST['ct_name'];    

// name from the form
    $email   = @$_POST['ct_email'];  

// email from the form
    $URL     = @$_POST['ct_URL'];    

// url from the form
    $message = @$_POST['ct_message'];

// the message from the form
    $captcha = @$_POST['ct_captcha'];

// the user's entry for the captcha code
    $name    = substr($name, 0, 64);  

// limit name to 64 characters

    $errors = array();  

// initialize empty error array

    if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
      // only check for errors if the form is not in debug mode

      if (strlen($name) < 3) {
       

// name too short, add error
        $errors['name_error'] = 'Your name is required';
      }

      if (strlen($email) == 0) {
       

// no email address given
        $errors['email_error'] = 'Email address is required';
      } else if ( !preg_match('/^(?:[\w\d]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $email)) {
       

// invalid email format
        $errors['email_error'] = 'Email address entered is invalid';
      }

      if (strlen($message) < 20) {
       

// message length too short
        $errors['message_error'] = 'Please enter a message';
      }
    }

   

// Only try to validate the captcha if the form has no errors
    // This is especially important for ajax calls
    if (sizeof($errors) == 0) {
      require_once dirname(__FILE__) . '/securimage.php';
      $securimage = new Securimage();

      if ($securimage->check($captcha) == false) {
        $errors['captcha_error'] = 'Incorrect security code entered<br />';
      }
    }

    if (sizeof($errors) == 0) {
     

// no errors, send the form
      $time       = date('r');
      $message = "A message was submitted from the contact form.  The following information was provided.<br /><br />"
                    . "Name: $name<br />"
                    . "Email: $email<br />"
                    . "URL: $URL<br />"
                    . "Message:<br />"
                    . "<pre>$message</pre>"
                    . "<br /><br />IP Address: {$_SERVER['REMOTE_ADDR']}<br />"
                    . "Time: $time<br />"
                    . "Browser: {$_SERVER['HTTP_USER_AGENT']}<br />";

      $message = wordwrap($message, 70);

      if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) {
            

// send the message with mail()
        mail($GLOBALS['ct_recipient'], $GLOBALS['ct_msg_subject'], $message, "From: {$GLOBALS['ct_recipient']}\r\nReply-To: {$email}\r\nContent-type: text/html; charset=ISO-8859-1\r\nMIME-Version: 1.0");
      }

      $_SESSION['ctform']['error'] = false;  

// no error with form
      $_SESSION['ctform']['success'] = true;

// message sent
    } else {
      // save the entries, this is to re-populate the form
      $_SESSION['ctform']['ct_name'] = $name;      

// save name from the form submission
      $_SESSION['ctform']['ct_email'] = $email;    

// save email
      $_SESSION['ctform']['ct_URL'] = $URL;        

// save URL
      $_SESSION['ctform']['ct_message'] = $message;

// save message

      foreach($errors as $key => $error) {
            

// set up error messages to display with each field
        $_SESSION['ctform'][$key] = "<span style=\"font-weight: bold; color: #f00\">$error</span>";
      }

      $_SESSION['ctform']['error'] = true; // set error floag
    }
  }

// POST
}

$_SESSION['ctform']['success'] = false; // clear success value after running 

Open in new window

(Edited to move the code into the code snippet)
0
rporter45Author Commented:
Thank you Ray.  Sorry.
0
rporter45Author Commented:
I have written my own code that allows me to do what I need on two separate php pages.  My preference would still be to complete on one php where the page submits to itself with validation and then a submit to URL if successful so will keep this question open for now in the hopes that someone can still assist.

Thank you in advance.

R.
0
Ray PaseurCommented:
I don't think I can modify your code for you, but I can show you the general design that allows an HTML form to be embedded in the same script file with the PHP action script.  If you do not include a URL of the action script, the browser will submit the request to the current URL.
http://www.laprbass.com/RAY_temp_rporter45.php

<?php // RAY_temp_rporter45.php
error_reporting(E_ALL);


// http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28265627.html#a39570011
// PHP ACTION SCRIPT IN THE SAME FILE WITH HTML FORM SCRIPT


// IF THERE WAS A POST-METHOD REQUEST
if (!empty($_POST))
{
    // SHOW THE REQUEST VARIABLES
    var_dump($_POST);

    // ACTIVATE THIS IF YOU WANT TO STOP THE SCRIPT FROM SHOWING THE FORM OVER AND OVER
    // die();
}

// CREATE SOME DATA (MAYBE CREATE AN ENTIRE WEB PAGE WITH DATA BASE LOOKUPS, ETC)
$now = date('r');

// CREATE THE HTML FORM USING HEREDOC NOTATIONH
$form = <<<EOD
<form method="post">
<input type="hidden" name="now" value="$now" />
Enter something:
<input name="something" />
<input type="submit" />
</form>
EOD;

// WRITE THE FORM
echo $form;

Open in new window

HTH, ~Ray
0
rporter45Author Commented:
Where is URL specified to forward to as the form action?
0
Ray PaseurCommented:
Great question.
If you do not include a URL of the action script, the browser will submit the request to the current URL.
http://www.w3.org/TR/html401/interact/forms.html
0
rporter45Author Commented:
I want it to submit to itself the first time in order to validate the form.  If successful validation, I want it to submit to another URL.
0
Dave BaldwinFixer of ProblemsCommented:
Actually, the only way to submit it to a second page is to gather the information and do a curl() routine to re-POST it.  When you submit the form the first time, all the information is sent to the server which passes it on to PHP.  If you use a 'header' redirect, the POSTed info will not be included.
0
rporter45Author Commented:
How would I use a CURL() to complete what you suggest?
0
Ray PaseurCommented:
Web applications aren't normally designed that way. A professional approach would incorporate the "another URL" functionality into the validation script in a way that would cause it to be executed after the validation is successful, and not executed if the validation fails.

Technically speaking you can submit all of the data from the validation script to another script, but it's unreasonably difficult to do so when compared to making a single request to a single script.  In order to do that double-submit process you would need to deconstruct the POST array into a urlencode() raw post string so you can use cURL or fsockopen() to send the data.  While this can be done, it's a fairly advanced exercise and it's full of all kinds of "fun stuff" including security issues that I would want to avoid.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
cURL documentation is on the PHP.net web site.
http://php.net/manual/en/book.curl.php

You'll also want to become familiar with this.
http://curl.haxx.se/libcurl/c/libcurl-errors.html

Take some food and water.  You're going on a long journey.
0
rporter45Author Commented:
I will stick with submitting to a second page to validate and submit to URL for now.  Thank you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.