Link to home
Start Free TrialLog in
Avatar of WLLadmin
WLLadmin

asked on

PHP not returning user form data on error

I have a web form and php processing page that will not return user form data on error.  If all required fields are filled out the form is successfully sent.  However, if either the email validation fails or the captcha validation fails, the error session is returned , but none of the form data.

Can someone please please tell me why the form does not function correctly and repost the session data?  see attached web form page and processing file. (saved as .txt)

Many thanks in-advance for your time and consideration.

:)
request-form-page.txt
process-page.txt
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

I can't take the time to debug your code right now, but I can show you the general design principle that lets a form remember its content from one request to the next.  This comes with the bonus of being able to highlight the errors, if any.
<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';
        // $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';
        // $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

In this example, we use the information that was posted to create a variable, or if nothing was posted, we have a NULL (lines 22-23).  We could also nullify the variables if, for example, they failed validation (lines 34 and 43).  By using HEREDOC notation to build the form (lines 57, et seq) the variables are automatically put back into the value attributes of the form input statements.

HTH, ~Ray
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
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
Avatar of WLLadmin
WLLadmin

ASKER

excellent...thank you very much for the info.  I am very new at PHP.  [Baptism by fire]  First thing i will do is fix the email function issue.  I will review your post and reply with the outcome (and quite possibly elaborate on the specifics of the issues im experiencing with this particular form)
Hi Ray,

I've rennovated the email validation (thanks again).  Now for the processing of the user form:

I have implemented onblur() and am using ajax validation to show the user if they miss requried fields even before they click the sumbit form button.  That being said, i need to figure out how to use php processing page to a) return the errored email field for the user to correct, and

b) also keep the form data they had already enetered.

On the form web page the required fields are in an array:
<? $required = array("Contact_Name", "CompanyName", "Phone", "CustomerEmail");
// form processor and captcha
include "formtest.php";?>

just before the <form> tag is more code - session ["error"] is returned when a form field is incorrect:
<?php
if ($_SESSION["error"]) {
      echo '<font color="red">' . $_SESSION["error"] . '</font>';
      unset($_SESSION["error"]);
}
?>

Each form field has a php var like:  [$form["abc"]

Also there is one hidden form:
<input type="hidden" name="print_blank_fields" value="1" />

On the processing page is a function to check required fields:
<% function verify_form($arrRequired, $arrPost) {

        foreach ($arrPost as $key=>$value) {
                if (in_array($key, $arrRequired) && $value == "") {
                    $_SESSION["error"] = 'Required form element <b>' . $key . '</b> cannot be   empty<br>';
return false;  }
        }
       return true;
}
%>

And HERE is the code i have for when the user sumbits the form (also the source of my troubles):

<? if ($_POST) {                         
 // save post into a cookie to retrieve later
    setcookie("form", serialize($_POST), time()+300);

    if (captcha::check()) {
             if (verify_form($required, $_POST))
      {
      //if the form is verified, we continue. Otherwise we will error out with redirect
      if ( (check_valid_email($_POST['CustomerEmail'])) )
      {
      // redirect to this url on full success and email form
      header('Location: http://mywebsite.html');
      $_POST['RemoteIP'] = $_SERVER['REMOTE_ADDR'];
      mail_form(SENDER, RECIPIENT, SUBJECT, $_POST);
      // email  form to the user
      mail_form(SENDER, CONTACTEML, SUBJECT, $_POST);
                 }
 else
{
// If not a valid email
$_SESSION["error"] = 'E-mail address is not valid  Please check Email address'.echo'<br/>';    
header('Location: ' . $_SERVER['HTTP_REFERER']);
  }
 exit;
}
else {
// If verify form failed
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
exit;
}
else {
// if not capture
$_SESSION["error"] = 'Verification word does not match';
header('Location: ' . $_SERVER['HTTP_REFERER']);
 }
exit;
}
else {
// if no $_POST variable
if ($HTTP_COOKIE_VARS['form']) {
//$form array can be used to set form field values
// this server sucks, need to remove added slashes
$form = unserialize(stripslashes($HTTP_COOKIE_VARS['form']));
// destroy cookie on client side
setcookie('form', '');
}
// echo $captcha puts captcha anywhere in the interface
$captcha = captcha::form("&rarr;&nbsp;");
}
%>


What AM i missing??
So iv'e thrown in $_SESSION['var'] for each $_POST value in my user form and at least now i can retrieve the posted text field data.  The only thing left to figure out are the option-select forms; they still do not return their values on post-back to the page.

  <select size="9" name="TargetCountries[ ]" multiple="multiple">
    <option <? if(in_array("USA", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="USA">USA</option>
    <option <? if (in_array("Australia", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="Australia">Australia</option>
    <option <? if (in_array("Canada", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="Canada">Canada</option>
    <option <? if (in_array("Europe", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="Europe">Europe</option>
    <option <? if (in_array("Japan", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="Japan">Japan</option>
    <option <? if (in_array("Korea", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="Korea">Korea</option>
    <option <? if (in_array("Taiwan", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="Taiwan">Taiwan</option>
    <option <? if (in_array("Other", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="Other">Other</option>
    <option <? if (in_array("N/A", $_SESSION['TargetCountries[ ]'])) echo "selected"; ?> value="N/A">N/A</option>
    </select>

When i select some or one or all of the options the post back is empty.
Is it syntax that may be causing the issue?
I just went ahead and created sessions.  This requred array and postback thing is not working as i have it, and i can't leave the form page 'out of order'.  Thanks for the help with email validation.