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
WLLadminAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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:
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
0
Ray PaseurCommented:
Sidebar note.  You will need to fix this.
   if (eregi($regexp, $_POST['CustomerEmail']))

Open in new window

See the large red warning label here.
http://us.php.net/manual/en/function.eregi.php

This has been a good-enough way for me to do email validation.  Maybe you can adapt it for your needs.
<?php // RAY_email_validation.php
error_reporting(E_ALL);


// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
// SEE MAN PAGE: http://php.net/manual/en/intro.filter.php
function check_valid_email($email)
{
    // LIST OF BLOCKED DOMAINS
    $bogus = array
    ( '@unknown.com'
    , '@example.com'
    , '@gooseball.org'
    )
    ;

    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }

    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                        // START REGEX DELIMITER
        . '^'                        // START STRING
        . '[A-Z0-9_-]'               // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'             // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                        // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+'  // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                  // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                    // TLD LENGTH >= 2 AND =< 6
        . '$'                        // ENDOF STRING
        . '/'                        // ENDOF REGEX DELIMITER
        . 'i'                        // CASE INSENSITIVE
        ;
        // TEST THE STRING FORMAT
        if (!preg_match($regex, $email)) return FALSE;
    }

    // TEST TO SEE IF THE DOMAIN IS IN OUR BLOCKED LIST
    foreach ($bogus as $badguy)
    {
        if (stripos($email, $badguy)) return FALSE;
    }

    // FILTER_VAR OR PREG_MATCH DOES NOT TEST IF THE DOMAIN IS ROUTABLE
    $domain = explode('@', $email);

    // MAN PAGE: http://php.net/manual/en/function.checkdnsrr.php
    if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") ) return TRUE;

    // EMAIL IS NOT ROUTABLE
    return FALSE;
}



// DEMONSTRATE THE FUNCTION IN ACTION
$e = NULL;
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e \n";
    }
    else
    {
        echo "<br/>BOGUS: $e \n";
    }
}


// END OF PROCESSING - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<form>
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="$e" />
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window

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
WLLadminAuthor Commented:
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)
0
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

WLLadminAuthor Commented:
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??
0
WLLadminAuthor Commented:
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?
0
WLLadminAuthor Commented:
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.
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
Web Development

From novice to tech pro — start learning today.