[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

PHP not returning user form data on error

Posted on 2012-03-13
8
Medium Priority
?
457 Views
Last Modified: 2014-09-07
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
0
Comment
Question by:WLLadmin
[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
  • 4
  • 2
8 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37714888
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
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 37714911
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
 

Author Comment

by:WLLadmin
ID: 37715045
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
Understanding Web Applications

Without even knowing it, most of us are using web applications on a daily basis. Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We often confuse these web applications tools for websites.  So, what is the difference?

 

Author Comment

by:WLLadmin
ID: 37716476
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
 

Author Comment

by:WLLadmin
ID: 37722602
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
 

Author Comment

by:WLLadmin
ID: 37823537
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Australian government abolished Visa 457 earlier this April and this article describes how this decision might affect Australian IT scene and IT experts.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…
Suggested Courses

656 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