Best approach for server side Form Validation ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • h7qvnk7q001@sneakemail.com

    Best approach for server side Form Validation ?

    I'm trying to implement a simple server-side form validation (No
    Javascript). If the user submits a form with errors, I want to
    redisplay the same form with the errors highlighted. Once the form is
    correct I need to submit to another page that uses the form data.

    I first tried making the form submit action= field point to the same
    file. When the form was correct, I tried loading the next page by using
    <META http-equiv refresh>. But that doesn't post the data, so the next
    page didn't have access to it.

    Then I tried changing the action= field of the form to an a PHP echo. I
    would echo a variable that was set to either "ThisSamePage.P HP" or
    "TheNextPage.PH P", depending on whether the validation was correct. The
    problem is that the user has to press Submit an extra time once the
    form is correct, since the form was still displayed with the action
    equal to "TheNextPage.PH P"

    I have looked for some way to submit the form directly from PHP code,
    but I don't know enough about PHP yet.

    I think I need some way to cause a Post action from PHP code, so I can
    get to the next page without redisplaying the form and having the user
    click submit again.

    Or is there a better way to structure this type of validation that
    avoids this issue?

  • Rik

    #2
    Re: Best approach for server side Form Validation ?

    h7qvnk7q001@sne akemail.com wrote:[color=blue]
    > I'm trying to implement a simple server-side form validation (No
    > Javascript). If the user submits a form with errors, I want to
    > redisplay the same form with the errors highlighted. Once the form is
    > correct I need to submit to another page that uses the form data.[/color]

    I assume the redisplaying & highlighting errors is not the problem?
    [color=blue]
    > I first tried making the form submit action= field point to the same
    > file. When the form was correct, I tried loading the next page by
    > using <META http-equiv refresh>. But that doesn't post the data, so
    > the next page didn't have access to it.[/color]

    In rederecting POST data is indeed lost.
    There are several solution:
    1. Use the same file for processing the data. (if it's a light application
    it's the easiest one).
    2. Use a temporary table in which you store the valid post data, preferably
    with some auto_incremente d key, which you can use as a GET variable on the
    redirect (major security leak: other visitors can see what the rest is
    doing).
    3. Use sessions, and store the valid posted data into the $_SESSION, use
    those values in the processing on the other page.

    Grtz,
    --
    Rik Wasmus


    Comment

    • Gordon Burditt

      #3
      Re: Best approach for server side Form Validation ?

      >I'm trying to implement a simple server-side form validation (No[color=blue]
      >Javascript). If the user submits a form with errors, I want to
      >redisplay the same form with the errors highlighted. Once the form is
      >correct I need to submit to another page that uses the form data.[/color]

      That would seem to make the validation trivial to bypass, unless,
      of course, you validate it AGAIN in the page that uses the form data.
      What is the purpose of this validation again?
      [color=blue]
      >I first tried making the form submit action= field point to the same
      >file. When the form was correct, I tried loading the next page by using
      ><META http-equiv refresh>. But that doesn't post the data, so the next
      >page didn't have access to it.[/color]

      You can't redirect a POST. And if the data goes through the user's
      browser, you can't trust it without validating it again.
      [color=blue]
      >Then I tried changing the action= field of the form to an a PHP echo. I
      >would echo a variable that was set to either "ThisSamePage.P HP" or
      >"TheNextPage.P HP", depending on whether the validation was correct. The
      >problem is that the user has to press Submit an extra time once the
      >form is correct, since the form was still displayed with the action
      >equal to "TheNextPage.PH P"
      >
      >I have looked for some way to submit the form directly from PHP code,
      >but I don't know enough about PHP yet.[/color]

      PHP can't control the user's browser like that, which is a good
      thing. This issue is one reason why Javascript is often Turned Off(tm).
      [color=blue]
      >I think I need some way to cause a Post action from PHP code, so I can
      >get to the next page without redisplaying the form and having the user
      >click submit again.[/color]

      It's possible to hit a page directly from the server with CURL, but
      I'd advise against this. Do the validation and processing in ONE
      hit.
      [color=blue]
      >Or is there a better way to structure this type of validation that
      >avoids this issue?[/color]

      Validate the input, then process it in the SAME hit. Perhaps use
      include(), but make sure the include()d file cannot be hit directly.

      Gordon L. Burditt

      Comment

      • planotravel.net

        #4
        Re: Best approach for server side Form Validation ?

        h7qvnk7q001 wrote:[color=blue]
        > I'm trying to implement a simple server-side form validation (No
        > Javascript). If the user submits a form with errors, I want to
        > redisplay the same form with the errors highlighted. Once the form is
        > correct I need to submit to another page that uses the form data.[/color]

        My solution for the recently started project was the following:

        Create three .php files

        1.php - (to initialize form variables) with a call to an A(2) function
        in 2.php with default parameters (0 for error variable, and an array of
        form elements)
        - 1.php is called when the user enters the form page

        2.php - (to print out and control the form) with the A(2) function that
        takes those two arguments
        - echo "<form action=3.php method=post>";
        - for each required field use:
        if ($error & n).{ echo "..."; } //where n is an error bit, e.g.,
        1,2,4,8,16,32 and so on.
        else { echo "..."; }
        - for all fields use interpolated array[x] value to , e.g., echo
        "<input type=text value=\"{$array["value"]}\">; - to return any
        previously entered data after page reload

        3.php - with a B() form validation function (checker) that is first
        called in 3.php
        - create, initialize and fill out the $array of form variables with
        user input
        - $error = 0; check the form data, assign $error a bit (1,2,4,8 etc.)
        if an error is found
        - if ($error != 0) { A(2); } else { do smth.,e,g, C(a,b,c); }


        - in 1.php and 3.php first do
        include '2.php';


        PS Go to http://www.planotravel.net, request a quote (yellow image),
        randomly fill out the form with errors, submit and see how it works.

        Good luck and Regards,

        planotravel.net

        Comment

        • Alan Little

          #5
          Re: Best approach for server side Form Validation ?

          Carved in mystic runes upon the very living rock, the last words of
          <h7qvnk7q001@sn eakemail.com> of comp.lang.php make plain:
          [color=blue]
          > I'm trying to implement a simple server-side form validation (No
          > Javascript). If the user submits a form with errors, I want to
          > redisplay the same form with the errors highlighted. Once the form is
          > correct I need to submit to another page that uses the form data.[/color]

          If you're interested in a pre-packaged solution rather than DIY, check out
          Phorm.

          --
          Alan Little
          Phorm PHP Form Processor

          Comment

          • Norman Peelman

            #6
            Re: Best approach for server side Form Validation ?

            "planotravel.ne t" <planotravel@gm ail.com> wrote in message
            news:1151208141 .299446.221630@ r2g2000cwb.goog legroups.com...[color=blue]
            > h7qvnk7q001 wrote:[color=green]
            > > I'm trying to implement a simple server-side form validation (No
            > > Javascript). If the user submits a form with errors, I want to
            > > redisplay the same form with the errors highlighted. Once the form is
            > > correct I need to submit to another page that uses the form data.[/color]
            >
            > My solution for the recently started project was the following:
            >
            > Create three .php files
            >
            > 1.php - (to initialize form variables) with a call to an A(2) function
            > in 2.php with default parameters (0 for error variable, and an array of
            > form elements)
            > - 1.php is called when the user enters the form page
            >
            > 2.php - (to print out and control the form) with the A(2) function that
            > takes those two arguments
            > - echo "<form action=3.php method=post>";
            > - for each required field use:
            > if ($error & n).{ echo "..."; } //where n is an error bit, e.g.,
            > 1,2,4,8,16,32 and so on.
            > else { echo "..."; }
            > - for all fields use interpolated array[x] value to , e.g., echo
            > "<input type=text value=\"{$array["value"]}\">; - to return any
            > previously entered data after page reload
            >
            > 3.php - with a B() form validation function (checker) that is first
            > called in 3.php
            > - create, initialize and fill out the $array of form variables with
            > user input
            > - $error = 0; check the form data, assign $error a bit (1,2,4,8 etc.)
            > if an error is found
            > - if ($error != 0) { A(2); } else { do smth.,e,g, C(a,b,c); }
            >
            >
            > - in 1.php and 3.php first do
            > include '2.php';
            >
            >
            > PS Go to http://www.planotravel.net, request a quote (yellow image),
            > randomly fill out the form with errors, submit and see how it works.
            >
            > Good luck and Regards,
            >
            > planotravel.net
            >[/color]

            What people are trying to say is that all three scripts can be combined
            into one. First an explanation. This snippet is incomplete in the sense that
            I am doing alot more behind the scenes. I am:

            1) using a template class to pre-populate the form fields and display the
            form which helps in providing clues to the user when fields are wrong
            2) requesting that the users click a check box that indicated they have read
            and agree to a waiver
            3) when the form is completed successfully I write the data to a database
            and place the user in an 'unregistered' state
            4) sending the user an email with a payment link should they not complete
            the payment process immediately
            5) updating the user to 'registered' upon completing the payment process.

            note-- the payment process (5) is a separate script (paypal)

            logfile('Start of request');
            $valid = 0; $not_required = 0;
            if (isset($_POST) && !empty($_POST))
            {
            // validate form field here - repeat code as neccessary for your form
            fields
            // ok - if we're here then the form has been submitted, lets check things
            out
            if (isset($_POST['pgfirstname']) && !empty($_POST['pgfirstname']))
            {
            // first name - allow letters only (case insensitive, 2 chars min - 25
            chars max)
            $pattern = "^[A-Za-z ]{2,25}$";
            if (ereg($pattern, $_POST['pgfirstname']))
            {
            // required field - update $valid by 1
            $valid++;
            // logfile() is a custom function
            logfile("Parent first name OK: $_POST[pgfirstname]");
            }
            else
            {
            // bad characters in field
            $pgfirstname_er ror = ' Sorry, you have invalid characters in your
            First name.';
            $pgfirstname_co lor = 'orange';
            logfile("Parent first name has invalid characters");
            }
            }
            else
            {
            // field was left empty
            $pgfirstname_er ror = ' We really need your First name (between 2 and
            25 letters only)';
            $pgfirstname_co lor = 'orange';
            logfile("Parent first name not submitted");
            }
            // variables are assigned correct or not as the form is repopulated so
            the user can correct typos
            $pgfirstname = $_POST['pgfirstname'];

            if (isset($_POST['address_em']) && !empty($_POST['address_em']))
            { // validate e-mail address as best we can...
            //$pattern =
            "^([A-Za-z0-9]+[._]?){1,}\+[A-Za-z0-9]+\@(([A-Za-z0-9]+[-]?){1,}[A-Za-z0-9]+
            \.){1,}[A-Za-z]{2,6}$";
            $pattern =
            "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.
            )+[a-zA-Z]{2,6}\$";
            //$pattern =
            "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.
            )+";
            //$pattern .= "([aero|biz|coop|c om|net]";
            //$pattern .= "{2,6}[\.]{0,})[ac|ad|ae|af|ag]{0,}\$";

            // stop unwanted email hosts here - add as many as needed
            $unwanted = array(0 => 'spamhole',
            1 => 'mytrashmail',
            2 => 'mailexpire',
            3 => 'spamgourmet',
            4 => 'mailinator',
            5 => 'woodyland',
            6 => 'spammotel',
            7 => 'sneakmail',
            8 => 'jetable'
            );
            foreach($unwant ed as $key => $value)
            { // create regex with $value... ex: spamhole{1}
            $value .= '{1}';
            if (eregi($value,$ _POST['address_em']))
            {
            logfile("WARN: email address is one of the unwanted email hosts
            $_POST[address_em]");
            $address_em_err or = "Temporary email addresses are not permitted!";
            $address_color = "orange";
            }
            }
            if (eregi($pattern ,$_POST['address_em']))
            {
            logfile("INFO: useremail passed email test -> $_POST[address_em]");
            $valid++;
            }
            else
            {
            logfile("INFO: Invalid email (useremail) address ->
            $_POST[address_em]");
            $address_em_err or = 'Invalid e-mail address! Please re-enter.';
            $address_em_col or = "orange";
            }
            }
            else
            {
            logfile("INFO: email address not submitted.");
            $address_em_err or = " We really need your email address.";
            $address_em_col or = "orange";
            }
            $address_em = $_POST['address_em'];
            }

            // validate cell phone - field NOT required for valid form
            if (isset($_POST['address_cph']) && !empty($_POST['address_cph']))
            {
            // cell phone - allow numbers only (case insensitive)
            $pattern = "^[0-9\-]{7,12}$";
            if (ereg($pattern, $_POST['address_cph']))
            {
            // if required, change this variable to $valid++
            // if not required change this variable to $not_required++
            $not_required++ ;
            }
            else
            {
            // we want valid input whether this field is required or not
            $address_cph_er ror = ' Sorry, you have improper characters in your
            Cell phone number.';
            $address_cph_co lor = 'orange';
            }
            }
            else
            {
            // if required, uncomment lines below
            //$address_cph_er ror = ' We really need your Cell phone number
            (xxx-xxx-xxxx format)';
            //$address_cph_co lor = 'orange';
            }
            $address_cph = $_POST['address_cph'];

            if (isset($_POST['waiveragree']) && !empty($_POST['waiveragree']) &&
            $_POST['waiveragree'] == 'agree')
            {
            // client has agreed to the waiver
            $waiveragree = 'checked';
            logfile("Client has agreed to waiver");
            }
            else
            {
            $waiveragree = '';
            $waiveragree_er ror = "You must agree to the waiver to complete the
            registration process.";
            $waiveragree_co lor = "orange";
            }


            // ok we've checked all the fields - count our required and not required
            fields to make sure everything is cool
            if ($valid == 2 && $not_required == 1 && @$_POST['waiveragree'] == 'agree')
            {
            // do something with user info
            logfile("INFO: Form completed correctly and client agreed to waiver");
            logfile("End of request");
            // you can redirect here...
            //header("Locatio n: hxxp://path.to.another .page?var1=$var 1&var2=$var2" );
            }

            ---



            --logfile()-- place at top of script
            define('LOGFILE ',true); // set to false to turn off logging.
            function logfile($txt)
            { // daily logging function - creates/appends a logfile by date
            if (LOGFILE)
            {
            $txt = date("G:i:s - ").$txt.chr(13) ;
            $lf = 'drive:\\path\t o\your\logfile_ name_'.date('D M j -
            Y').'.logfile';
            $fp = fopen($lf,'a');
            fwrite($fp,$txt ,1024);
            fclose($fp);
            } // assign the extension .logfile to WORDPAD or some other text reader
            that will format it correcly - just a quick and dirty function
            }

            ....some good examples of logfile usage are:

            logfile('MySQL: '.mysql_errno($ dbc).' - '.mysql_error($ dbc));
            logfile("INFO: some info here from a $variable");
            logfile("$scrip t_name: info here");
            etc.

            Norm


            Comment

            • Norman Peelman

              #7
              Re: Best approach for server side Form Validation ?

              "Norman Peelman" <npeelman@cfl.r r.com> wrote in message
              news:HFvng.1823 3$LT2.9955@torn ado.tampabay.rr .com...[color=blue]
              > "planotravel.ne t" <planotravel@gm ail.com> wrote in message
              > news:1151208141 .299446.221630@ r2g2000cwb.goog legroups.com...[color=green]
              > > h7qvnk7q001 wrote:[color=darkred]
              > > > I'm trying to implement a simple server-side form validation (No
              > > > Javascript). If the user submits a form with errors, I want to
              > > > redisplay the same form with the errors highlighted. Once the form is
              > > > correct I need to submit to another page that uses the form data.[/color]
              > >
              > > My solution for the recently started project was the following:
              > >
              > > Create three .php files
              > >
              > > 1.php - (to initialize form variables) with a call to an A(2) function
              > > in 2.php with default parameters (0 for error variable, and an array of
              > > form elements)
              > > - 1.php is called when the user enters the form page
              > >
              > > 2.php - (to print out and control the form) with the A(2) function that
              > > takes those two arguments
              > > - echo "<form action=3.php method=post>";
              > > - for each required field use:
              > > if ($error & n).{ echo "..."; } //where n is an error bit, e.g.,
              > > 1,2,4,8,16,32 and so on.
              > > else { echo "..."; }
              > > - for all fields use interpolated array[x] value to , e.g., echo
              > > "<input type=text value=\"{$array["value"]}\">; - to return any
              > > previously entered data after page reload
              > >
              > > 3.php - with a B() form validation function (checker) that is first
              > > called in 3.php
              > > - create, initialize and fill out the $array of form variables with
              > > user input
              > > - $error = 0; check the form data, assign $error a bit (1,2,4,8 etc.)
              > > if an error is found
              > > - if ($error != 0) { A(2); } else { do smth.,e,g, C(a,b,c); }
              > >
              > >
              > > - in 1.php and 3.php first do
              > > include '2.php';
              > >
              > >
              > > PS Go to http://www.planotravel.net, request a quote (yellow image),
              > > randomly fill out the form with errors, submit and see how it works.
              > >
              > > Good luck and Regards,
              > >
              > > planotravel.net
              > >[/color]
              >[/color]
              What people are trying to say is that all three scripts can be combined
              into one. First an explanation. This snippet is incomplete in the sense that
              I am doing alot more behind the scenes. I am:

              1) using a template class to pre-populate the form fields and display the
              form which helps in providing clues to the user when fields are wrong
              2) requesting that the users click a check box that indicated they have read
              and agree to a waiver
              3) when the form is completed successfully I write the data to a database
              and place the user in an 'unregistered' state
              4) sending the user an email with a payment link should they not complete
              the payment process immediately
              5) updating the user to 'registered' upon completing the payment process.

              note-- the payment process (5) is a separate script (paypal)

              logfile('Start of request');
              $valid = 0; $not_required = 0;
              if (isset($_POST) && !empty($_POST))
              {
              // validate form field here - repeat code as neccessary for your form
              fields
              // ok - if we're here then the form has been submitted, lets check things
              out
              if (isset($_POST['pgfirstname']) && !empty($_POST['pgfirstname']))
              {
              // first name - allow letters only (case insensitive, 2 chars min - 25
              chars max)
              $pattern = "^[A-Za-z ]{2,25}$";
              if (ereg($pattern, $_POST['pgfirstname']))
              {
              // required field - update $valid by 1
              $valid++;
              // logfile() is a custom function
              logfile("Parent first name OK: $_POST[pgfirstname]");
              }
              else
              {
              // bad characters in field
              $pgfirstname_er ror = ' Sorry, you have invalid characters in your
              First name.';
              $pgfirstname_co lor = 'orange';
              logfile("Parent first name has invalid characters");
              }
              }
              else
              {
              // field was left empty
              $pgfirstname_er ror = ' We really need your First name (between 2 and
              25 letters only)';
              $pgfirstname_co lor = 'orange';
              logfile("Parent first name not submitted");
              }
              // variables are assigned correct or not as the form is repopulated so
              the user can correct typos
              $pgfirstname = $_POST['pgfirstname'];

              if (isset($_POST['address_em']) && !empty($_POST['address_em']))
              { // validate e-mail address as best we can...
              //$pattern =
              "^([A-Za-z0-9]+[._]?){1,}\+[A-Za-z0-9]+\@(([A-Za-z0-9]+[-]?){1,}[A-Za-z0-9]+
              \.){1,}[A-Za-z]{2,6}$";
              $pattern =
              "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.
              )+[a-zA-Z]{2,6}\$";
              //$pattern =
              "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.
              )+";
              //$pattern .= "([aero|biz|coop|c om|net]";
              //$pattern .= "{2,6}[\.]{0,})[ac|ad|ae|af|ag]{0,}\$";

              // stop unwanted email hosts here - add as many as needed
              $unwanted = array(0 => 'spamhole',
              1 => 'mytrashmail',
              2 => 'mailexpire',
              3 => 'spamgourmet',
              4 => 'mailinator',
              5 => 'woodyland',
              6 => 'spammotel',
              7 => 'sneakmail',
              8 => 'jetable'
              );
              foreach($unwant ed as $key => $value)
              { // create regex with $value... ex: spamhole{1}
              $value .= '{1}';
              if (eregi($value,$ _POST['address_em']))
              {
              logfile("WARN: email address is one of the unwanted email hosts
              $_POST[address_em]");
              $address_em_err or = "Temporary email addresses are not permitted!";
              $address_color = "orange";
              }
              }
              if (eregi($pattern ,$_POST['address_em']))
              {
              logfile("INFO: useremail passed email test -> $_POST[address_em]");
              $valid++;
              }
              else
              {
              logfile("INFO: Invalid email (useremail) address ->
              $_POST[address_em]");
              $address_em_err or = 'Invalid e-mail address! Please re-enter.';
              $address_em_col or = "orange";
              }
              }
              else
              {
              logfile("INFO: email address not submitted.");
              $address_em_err or = " We really need your email address.";
              $address_em_col or = "orange";
              }
              $address_em = $_POST['address_em'];
              }

              // validate cell phone - field NOT required for valid form
              if (isset($_POST['address_cph']) && !empty($_POST['address_cph']))
              {
              // cell phone - allow numbers only (case insensitive)
              $pattern = "^[0-9\-]{7,12}$";
              if (ereg($pattern, $_POST['address_cph']))
              {
              // if required, change this variable to $valid++
              // if not required change this variable to $not_required++
              $not_required++ ;
              }
              else
              {
              // we want valid input whether this field is required or not
              $address_cph_er ror = ' Sorry, you have improper characters in your
              Cell phone number.';
              $address_cph_co lor = 'orange';
              }
              }
              else
              {
              // if required, uncomment lines below
              //$address_cph_er ror = ' We really need your Cell phone number
              (xxx-xxx-xxxx format)';
              //$address_cph_co lor = 'orange';
              $not_required++ ;
              }
              $address_cph = $_POST['address_cph'];

              if (isset($_POST['waiveragree']) && !empty($_POST['waiveragree']) &&
              $_POST['waiveragree'] == 'agree')
              {
              // client has agreed to the waiver
              $waiveragree = 'checked';
              logfile("Client has agreed to waiver");
              }
              else
              {
              $waiveragree = '';
              $waiveragree_er ror = "You must agree to the waiver to complete the
              registration process.";
              $waiveragree_co lor = "orange";
              }


              // ok we've checked all the fields - count our required and not required
              fields to make sure everything is cool
              if ($valid == 2 && $not_required == 1 && @$_POST['waiveragree'] == 'agree')
              {
              // do something with user info
              logfile("INFO: Form completed correctly and client agreed to waiver");
              logfile("End of request");
              // you can redirect here...
              //header("Locatio n: hxxp://path.to.another .page?var1=$var 1&var2=$var2" );
              }

              ---



              --logfile()-- place at top of script
              define('LOGFILE ',true); // set to false to turn off logging.
              function logfile($txt)
              { // daily logging function - creates/appends a logfile by date
              if (LOGFILE)
              {
              $txt = date("G:i:s - ").$txt.chr(13) ;
              $lf = 'drive:\\path\t o\your\logfile_ name_'.date('D M j -
              Y').'.logfile';
              $fp = fopen($lf,'a');
              fwrite($fp,$txt ,1024);
              fclose($fp);
              } // assign the extension .logfile to WORDPAD or some other text reader
              that will format it correcly - just a quick and dirty function
              }

              ....some good examples of logfile usage are:

              logfile('MySQL: '.mysql_errno($ dbc).' - '.mysql_error($ dbc));
              logfile("INFO: some info here from a $variable");
              logfile("$scrip t_name: info here");
              etc.

              The *_color variables are used by the CSS/STYLE to colorize the form fields
              on error, the *_error variables are self explanatory. And as you can see you
              can customize the errors to reflect the true problems.


              Norm



              Comment

              • Norman Peelman

                #8
                Re: Best approach for server side Form Validation ?

                edit near bottom...

                --
                FREE Avatar hosting at www.easyavatar.com
                "Norman Peelman" <npeelman@cfl.r r.com> wrote in message
                news:adwng.2901 8$Ui7.24862@tor nado.tampabay.r r.com...[color=blue]
                > "Norman Peelman" <npeelman@cfl.r r.com> wrote in message
                > news:HFvng.1823 3$LT2.9955@torn ado.tampabay.rr .com...[color=green]
                > > "planotravel.ne t" <planotravel@gm ail.com> wrote in message
                > > news:1151208141 .299446.221630@ r2g2000cwb.goog legroups.com...[color=darkred]
                > > > h7qvnk7q001 wrote:
                > > > > I'm trying to implement a simple server-side form validation (No
                > > > > Javascript). If the user submits a form with errors, I want to
                > > > > redisplay the same form with the errors highlighted. Once the form[/color][/color][/color]
                is[color=blue][color=green][color=darkred]
                > > > > correct I need to submit to another page that uses the form data.
                > > >
                > > > My solution for the recently started project was the following:
                > > >
                > > > Create three .php files
                > > >
                > > > 1.php - (to initialize form variables) with a call to an A(2) function
                > > > in 2.php with default parameters (0 for error variable, and an array[/color][/color][/color]
                of[color=blue][color=green][color=darkred]
                > > > form elements)
                > > > - 1.php is called when the user enters the form page
                > > >
                > > > 2.php - (to print out and control the form) with the A(2) function[/color][/color][/color]
                that[color=blue][color=green][color=darkred]
                > > > takes those two arguments
                > > > - echo "<form action=3.php method=post>";
                > > > - for each required field use:
                > > > if ($error & n).{ echo "..."; } //where n is an error bit, e.g.,
                > > > 1,2,4,8,16,32 and so on.
                > > > else { echo "..."; }
                > > > - for all fields use interpolated array[x] value to , e.g., echo
                > > > "<input type=text value=\"{$array["value"]}\">; - to return any
                > > > previously entered data after page reload
                > > >
                > > > 3.php - with a B() form validation function (checker) that is first
                > > > called in 3.php
                > > > - create, initialize and fill out the $array of form variables with
                > > > user input
                > > > - $error = 0; check the form data, assign $error a bit (1,2,4,8 etc.)
                > > > if an error is found
                > > > - if ($error != 0) { A(2); } else { do smth.,e,g, C(a,b,c); }
                > > >
                > > >
                > > > - in 1.php and 3.php first do
                > > > include '2.php';
                > > >
                > > >
                > > > PS Go to http://www.planotravel.net, request a quote (yellow image),
                > > > randomly fill out the form with errors, submit and see how it works.
                > > >
                > > > Good luck and Regards,
                > > >
                > > > planotravel.net
                > > >[/color]
                > >[/color][/color]
                What people are trying to say is that all three scripts can be combined
                into one. First an explanation. This snippet is incomplete in the sense that
                I am doing alot more behind the scenes. I am:

                1) using a template class to pre-populate the form fields and display the
                form which helps in providing clues to the user when fields are wrong
                2) requesting that the users click a check box that indicated they have read
                and agree to a waiver
                3) when the form is completed successfully I write the data to a database
                and place the user in an 'unregistered' state
                4) sending the user an email with a payment link should they not complete
                the payment process immediately
                5) updating the user to 'registered' upon completing the payment process.

                note-- the payment process (5) is a separate script (paypal)

                logfile('Start of request');
                $valid = 0; $not_required = 0;
                if (isset($_POST) && !empty($_POST))
                {
                // validate form field here - repeat code as neccessary for your form
                fields
                // ok - if we're here then the form has been submitted, lets check things
                out
                if (isset($_POST['pgfirstname']) && !empty($_POST['pgfirstname']))
                {
                // first name - allow letters only (case insensitive, 2 chars min - 25
                chars max)
                $pattern = "^[A-Za-z ]{2,25}$";
                if (ereg($pattern, $_POST['pgfirstname']))
                {
                // required field - update $valid by 1
                $valid++;
                // logfile() is a custom function
                logfile("Parent first name OK: $_POST[pgfirstname]");
                }
                else
                {
                // bad characters in field
                $pgfirstname_er ror = ' Sorry, you have invalid characters in your
                First name.';
                $pgfirstname_co lor = 'orange';
                logfile("Parent first name has invalid characters");
                }
                }
                else
                {
                // field was left empty
                $pgfirstname_er ror = ' We really need your First name (between 2 and
                25 letters only)';
                $pgfirstname_co lor = 'orange';
                logfile("Parent first name not submitted");
                }
                // variables are assigned correct or not as the form is repopulated so
                the user can correct typos
                $pgfirstname = $_POST['pgfirstname'];

                if (isset($_POST['address_em']) && !empty($_POST['address_em']))
                { // validate e-mail address as best we can...
                //$pattern =
                "^([A-Za-z0-9]+[._]?){1,}\+[A-Za-z0-9]+\@(([A-Za-z0-9]+[-]?){1,}[A-Za-z0-9]+
                \.){1,}[A-Za-z]{2,6}$";
                $pattern =
                "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.
                )+[a-zA-Z]{2,6}\$";
                //$pattern =
                "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.
                )+";
                //$pattern .= "([aero|biz|coop|c om|net]";
                //$pattern .= "{2,6}[\.]{0,})[ac|ad|ae|af|ag]{0,}\$";

                // stop unwanted email hosts here - add as many as needed
                $unwanted = array(0 => 'spamhole',
                1 => 'mytrashmail',
                2 => 'mailexpire',
                3 => 'spamgourmet',
                4 => 'mailinator',
                5 => 'woodyland',
                6 => 'spammotel',
                7 => 'sneakmail',
                8 => 'jetable'
                );
                foreach($unwant ed as $key => $value)
                { // create regex with $value... ex: spamhole{1}
                $value .= '{1}';
                if (eregi($value,$ _POST['address_em']))
                {
                logfile("WARN: email address is one of the unwanted email hosts
                $_POST[address_em]");
                $address_em_err or = "Temporary email addresses are not permitted!";
                $address_color = "orange";
                }
                }
                if (eregi($pattern ,$_POST['address_em']))
                {
                logfile("INFO: useremail passed email test -> $_POST[address_em]");
                $valid++;
                }
                else
                {
                logfile("INFO: Invalid email (useremail) address ->
                $_POST[address_em]");
                $address_em_err or = 'Invalid e-mail address! Please re-enter.';
                $address_em_col or = "orange";
                }
                }
                else
                {
                logfile("INFO: email address not submitted.");
                $address_em_err or = " We really need your email address.";
                $address_em_col or = "orange";
                }
                $address_em = $_POST['address_em'];
                }

                // validate cell phone - field NOT required for valid form
                if (isset($_POST['address_cph']) && !empty($_POST['address_cph']))
                {
                // cell phone - allow numbers only (case insensitive)
                $pattern = "^[0-9\-]{7,12}$";
                if (ereg($pattern, $_POST['address_cph']))
                {
                // if required, change this variable to $valid++
                // if not required change this variable to $not_required++
                $not_required++ ;
                }
                else
                {
                // we want valid input whether this field is required or not
                $address_cph_er ror = ' Sorry, you have improper characters in your
                Cell phone number.';
                $address_cph_co lor = 'orange';
                }
                }
                else
                {
                // if required, uncomment lines below
                //$address_cph_er ror = ' We really need your Cell phone number
                (xxx-xxx-xxxx format)';
                //$address_cph_co lor = 'orange';
                $not_required++ ;
                }
                $address_cph = $_POST['address_cph'];

                if (isset($_POST['waiveragree']) && !empty($_POST['waiveragree']) &&
                $_POST['waiveragree'] == 'agree')
                {
                // client has agreed to the waiver
                $waiveragree = 'checked';
                logfile("Client has agreed to waiver");
                }
                else
                {
                $waiveragree = '';
                $waiveragree_er ror = "You must agree to the waiver to complete the
                registration process.";
                $waiveragree_co lor = "orange";
                }


                // ok we've checked all the fields - count our required and not required
                fields to make sure everything is cool
                if ($valid == 2 && $not_required == 1 && @$_POST['waiveragree'] == 'agree')
                {
                // do something with user info
                logfile("INFO: Form completed correctly and client agreed to waiver");
                logfile("End of request");
                // you can redirect here...
                //header("Locatio n: hxxp://path.to.another .page?var1=$var 1&var2=$var2" );
                }
                }
                else
                {
                display the form
                }

                ---



                --logfile()-- place at top of script
                define('LOGFILE ',true); // set to false to turn off logging.
                function logfile($txt)
                { // daily logging function - creates/appends a logfile by date
                if (LOGFILE)
                {
                $txt = date("G:i:s - ").$txt.chr(13) ;
                $lf = 'drive:\\path\t o\your\logfile_ name_'.date('D M j -
                Y').'.logfile';
                $fp = fopen($lf,'a');
                fwrite($fp,$txt ,1024);
                fclose($fp);
                } // assign the extension .logfile to WORDPAD or some other text reader
                that will format it correcly - just a quick and dirty function
                }

                ....some good examples of logfile usage are:

                logfile('MySQL: '.mysql_errno($ dbc).' - '.mysql_error($ dbc));
                logfile("INFO: some info here from a $variable");
                logfile("$scrip t_name: info here");
                etc.

                The *_color variables are used by the CSS/STYLE to colorize the form fields
                on error, the *_error variables are self explanatory. And as you can see you
                can customize the errors to reflect the true problems.


                Norm




                Comment

                Working...