Jump to content

Recommended Posts

Hello playERZ'

 

So, I have a dinky contact form that validates and uses:

<form name="infoget" action="<?=$_SERVER['PHP_SELF']?>" method="post">

to validate the form via an external validate.php, then generate the email.

 

Finally:

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
header("Location:customize_search.php");

 

So, this takes the user to a more advanced form after they 'send' the first form.

 

1 - Is it possible to have the second form autofill with the POSTed data and NOT use MySQL or database whatever?

2 - If so, how??

Link to comment
https://forums.phpfreaks.com/topic/211128-php-autofill-without-mysql-database/
Share on other sites

1. Yes.

2. return the posted data to the page.

 

NOTE, the first code section you posted, says that the form is posting to it's own page.  Putting the mail function at the top of that page with a few data checks is all you need to easily post the data back to the form.  If you post your entire script, then we can get it sorted for you fairly quickly.

8)Thanks for the superfast reply

I hope what I post below is what you are asking for.

If you need more just let a brother know!

 

$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
$success_message = "";

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,first_name,Enter your name.";
  $rules[] = "required,email,Enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

// Length of field input
  $rules[] = "length=10,phone,Please enter a ten digit Phone number.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    $fields = $_POST;
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    $to = "info@fieldsof.corn";
$subject = "Most Amazing Email Form Ever";
$field_first = $_POST['first_name'];
$field_email = $_POST['email'];
$field_phone = $_POST['phone'];

$body = "Name: $field_first\n Email: $field_email\n Phone: $field_phone\n ";

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
header("Location:customize_search.php");
  }
}

 

Then the form starts:

      <form name="infoget" action="<?=$_SERVER['PHP_SELF']?>" method="post">
        <fieldset>

 

Then inside the form, I'm using:

    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:90%;'>Please fix the following errors:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }

 

Then a little bit of this:

            <label for="first_name">Name &#42;
              <input type="text" name="first_name" id="first_name" value="<?=$_POST['first_name']?>" />
            </label>

 

And finally:

<input class="button" type="image" name="submit" id="submit" value="submit" src="images/send.gif" width="192" height="69" />
            <input type="hidden" name="submit" value="submit" />

@ Pikachu2000

LOL. Oh! You meant what you typed, go figure  :D

 

It seems to be working fine.

So, why would some crazy joker say I should put that PHP_SELF nonsense in the file - Although, I might have found it in a thread from 2004... who knows??

You are looking to put the posted data into the form on the "customize_search.php" page?

 

You could pass them onto that page in one of two ways.

 

1. Set them to session variables.

2. pass them as Get parameters inside the Location url.

Okay, well I've tested a simple 2-page setup for passing data from one page to another to test to see if everything is configured properly, and it seems to work.

 

I just can't figure it out for my situation...

 

PAGE 1 \\\\\\\\\\\\\\\\\\\\\\\\\\\\

session_start(); // start PHP session to pass temp variables to next page 
$_SESSION['email']; // store session data
$_SESSION['phone']; // store session data

$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
$success_message = "";

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,first_name,Enter your name.";
  $rules[] = "required,email,Enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

// Length of field input
  $rules[] = "length=10,phone,Please enter a ten digit Phone number.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    $fields = $_POST;
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    $to = "info@blabla.com";
$subject = "Free blabla";
$field_first = $_POST['first_name'];
$field_email = $_POST['email'];
$field_phone = $_POST['phone'];

$body = "Name: $field_first\n Email: $field_email\n Phone: $field_phone\n ";

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
header("Location:test_customize_search.php");
  }
}

 

      <form name="infoget" action="" method="post">
        <fieldset>

 

    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:90%;'>Please fix the following errors:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }

 

            <label for="email">Email &#42;
              <input type="text" name="email" id="email" value="<?=$fields['email']?>" />
            </label>
            <label for="phone"><input type="text" name="phone" id="phone" value="<?=$fields['phone']?>" /><span style="float:left">Phone &#42;</span><br />
            <span style="font-size:9px; float:left; width:100px;">(Ten digits, no dashes)</span>
          </label>

 

PAGE 2 \\\\\\\\\\\\\\\\\\\\\\\\\\\\

session_start();

$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
$success_message = "";

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,first_name,Enter your first name.";
  $rules[] = "required,last_name,Enter your last name.";
  $rules[] = "required,email,Enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

// Length of field input
  $rules[] = "length=10,phone,Please enter a ten digit phone number - No dashes.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    $fields = $_POST;
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    $to = "info@blabla.com";
$subject = "Customized blabla";
$field_first = $_POST['first_name'];
$field_last = $_POST['last_name'];
$field_email = $_POST['email'];
$field_phone = $_POST['phone'];
$field_proptype = $_POST['prop_type'];
$field_propcat = $_POST['prop_cat'];
$field_pricemin = $_POST['price_min'];
$field_pricemax = $_POST['price_max'];
$field_propsq = $_POST['prop_sq'];
$field_propbed = $_POST['prop_bed'];
$field_propbath = $_POST['prop_bath'];
$field_propplans = $_POST['prop_plans'];
$field_area = $_POST['area'];
$field_city = $_POST['city'];

$body = "First Name: $field_first\n Last Name: $field_last\n Email: $field_email\n Phone: $field_phone\n Property Type: $field_proptype\n Buying Category: $field_propcat\n Minimum Price: $field_pricemin\n Maximum Price: $field_pricemax\n Sq. Ft.: $field_propsq\n Bedrooms: $field_propbed\n Bathrooms: $field_propbath\n Moving Plans: $field_propplans\n Area: $field_area\n City or Zip: $field_city\n ";

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
header("Location: thank_you.htm");
  }
}

 

<form name="infoget" id="fm-form" method="post" action="" >
  <h4 id="fm-intro" style="background: #666; color: #FFF">Customize Your blabla</h4>
    <fieldset>

 

    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:90%;'>Please fix the following:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }

 

      <label class="fm-req" for="email">Email*</label>
        <input class="fm-req" id="email" name="email" type="text" value="<?php echo $_SESSION['email']; ?>" >
      <label class="fm-req" for="phone">Telephone* <span style="font-weight:normal">(10 digits - no dashes)</span></label>
        <input class="fm-req" id="phone" name="phone" title="10-Digit Phone Number, No Dashes" type="text" value="<?php echo $_SESSION['phone']; ?>">

Here's a more complete set of what I'm working with...

 

PAGE 1 - index.php

 

<?php

$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
$success_message = "";

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,first_name,Enter your name.";
  $rules[] = "required,email,Enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

// Length of field input
  $rules[] = "length=10,phone,Please enter a ten digit Phone number.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    $fields = $_POST;
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    $to = "info@site.com";
$subject = "Site Info";
$field_first = $_POST['first_name'];
$field_email = $_POST['email'];
$field_phone = $_POST['phone'];

$body = "Name: $field_first\n Email: $field_email\n Phone: $field_phone\n ";

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
header("Location:customize_search.php");
  }
}
          
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Page title</title>
<meta name="keywords" content="..." />
<meta name="description" content="..." />

<link href="css/style_reset.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/form_style.css" rel="stylesheet" type="text/css" media="screen" />

<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon" />
</head>

<body>
<div id="outer">
  <div class="conleft">
    <div class="conttopad"></div>
    <div class="continner">

    </div><!-- End Content Inner -->
  </div><!-- End Content Left -->
  <div class="conright">
    <div class="conttopad"></div>
    <div class="continner">

<p style=" font-size:13px; text-align:center; line-height:16px">Enter your contact information in the form below…</p>

      <form action="" method="post">
        <fieldset>

<?php

    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:90%;'>Please fix the following errors:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }
?>

            <label for="first_name">Name &#42;
              <input type="text" name="first_name" id="first_name" value="<?=$_POST['first_name']?>" />
            </label>
            <label for="email">Email &#42;
              <input type="text" name="email" id="email" value="<?=$fields['email']?>" />
            </label>
		<label for="phone"><input type="text" name="phone" id="phone" value="<?=$fields['phone']?>" /><span style="float:left">Phone &#42;</span><br />
            <span style="font-size:9px; float:left; width:100px;">(Ten digits, no dashes)</span>
              
          </label>
          </fieldset>
    <fieldset style=" clear:both">
            <input class="button" type="image" name="submit" id="submit" value="submit" src="images/send.gif" width="192" height="69" />
            <input type="hidden" name="submit" value="submit" />
          </fieldset>
        </form>
<div style="clear:both"></div>
<p style=" font-size:11px; text-align:center; line-height:16px; color:#737373; clear:left; margin-top:12px"><strong>**Please double-check</strong> that your email address is correct or you won't be able to get all the free training material. I take your privacy
very seriously - your information is NEVER shared.</p>
</div><!-- End Content inner -->
  </div><!-- End Content Right -->
</div><!-- End Outer -->
<div style="clear:both;"></div>
<div id="footer">
<div id="footerinner" style="width:880px">
<div class="conleft" style="width:530px">
</div>
<div class="conright" style="width:350px"></div>
<div style="clear:both;"></div>
</div><!-- End Footer Inner -->
</div><!-- End Footer -->
</body>
</html>

 

 

PAGE 2 - customize_search.php

 

<?php

$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
$success_message = "";

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,first_name,Enter your first name.";
  $rules[] = "required,last_name,Enter your last name.";
  $rules[] = "required,email,Enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

// Length of field input
  $rules[] = "length=10,phone,Please enter a ten digit phone number - No dashes.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    $fields = $_POST;
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    $to = "info@site.com";
$subject = "Customized List";
$field_first = $_POST['first_name'];
$field_last = $_POST['last_name'];
$field_email = $_POST['email'];
$field_phone = $_POST['phone'];

$body = "First Name: $field_first\n Last Name: $field_last\n Email: $field_email\n Phone: $field_phone\n ";

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
header("Location: thank_you.htm");
  }
}
          
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Page Title</title>
<meta name="keywords"..." />
<meta name="description" content="..." />

<link href="css/style_reset.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/form_style_p2.css" rel="stylesheet" type="text/css" media="screen" />

<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="css/style_ie7.css" />
<![endif]-->

<!--[if lte IE 7]>
<link rel="stylesheet" type="text/css" href="css/style_ie7.css" />
<![endif]-->

<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon" />
</head>

<body>
<div id="outer">
  <div class="consingle">
    <div class="conttopad" style="background:url(images/topad.gif) no-repeat top center"></div>
    <div class="continner">

<div>
<form id="fm-form" method="post" action="" >
  <h4 id="fm-intro" style="background: #666; color: #FFF">Text</h4>
    <fieldset>
<?php

    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:90%;'>Please fix the following:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }
?>

      <label class="fm-req" for="firstname">First name*</label>
        <input class="fm-req" name="first_name" id="first_name" type="text" value="<?=$fields['first_name']?>" >
      <label class="fm-req" for="lastname">Last name*</label>
        <input class="fm-req" name="last_name" id="last_name" type="text" value="<?=$fields['last_name']?>" >
      <label class="fm-req" for="email">Email*</label>
        <input class="fm-req" id="email" name="email" type="text" value="<?=$fields['email']?>" >
      <label class="fm-req" for="phone">Telephone* <span style="font-weight:normal">(10 digits - no dashes)</span></label>
        <input class="fm-req" id="phone" name="phone" title="10-Digit Phone Number, No Dashes" type="text" value="<?=$fields['phone']?>">
    </fieldset>

<div id="sub">
      <input class="fm-req" id="fm-submit" name="submit" value="Send My Info" type="submit">
      <input type="hidden" name="submitted" value="TRUE" >
</div>
  </form>
</div>

<div style="clear:both"></div>

<div class="conlist">

</div>

    </div><!-- End Content Inner -->
  </div><!-- End Content Single -->
</div><!-- End Outer -->
<div style="clear:both;"></div>
<div id="footer">
<div id="footerinner">
<div class="consingle">

</div>

<div style="clear:both;"></div>
</div><!-- End Footer Inner -->
</div><!-- End Footer -->
</body>
</html>

 

 

VALIDATION DOC - validation.php

 

<?php

/*--------------------------------------------------------------------------------------------*\

  validation.php
  --------------

  v2.3.3, Apr 2010

  This script provides generic validation for any web form. For a discussion and example usage 
  of this script, go to http://www.benjaminkeen.com/software/php_validation

  This script is written by Ben Keen with additional code contributed by Mihai Ionescu and 
  Nathan Howard. It is free to distribute, to re-write - to do what ever you want with it.

  Before using it, please read the following disclaimer. 

  THIS SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS WITHOUT WARRANTY OF ANY KIND. BENJAMINKEEN.COM 
  SPECIFICALLY DISCLAIMS ANY OTHER WARRANTY, EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF 
  MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL BENJAMINKEEN.COM BE 
  LIABLE FOR ANY CONSEQUENTIAL, INDIRECT, SPECIAL OR INCIDENTAL DAMAGES, EVEN IF BENJAMINKEEN.COM 
  HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH POTENTIAL LOSS OR DAMAGE. USER AGREES TO HOLD 
  BENJAMINKEEN.COM HARMLESS FROM AND AGAINST ANY AND ALL CLAIMS, LOSSES, LIABILITIES AND EXPENSES.

\*--------------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------------*\
  Function: validateFields()
  Purpose:  generic form field validation.
  Parameters: field - the POST / GET fields from a form which need to be validated.
              rules - an array of the validation rules. Each rule is a string of the form:

   "[if:FIELDNAME=VALUE,]REQUIREMENT,fieldname[,fieldname2 [,fieldname3, date_flag]],error message"
  
              if:FIELDNAME=VALUE,   This allows us to only validate a field 
                          only if a fieldname FIELDNAME has a value VALUE. This 
                          option allows for nesting; i.e. you can have multiple 
                          if clauses, separated by a comma. They will be examined
                          in the order in which they appear in the line.

              Valid REQUIREMENT strings are: 
                "required"     - field must be filled in
                "digits_only"  - field must contain digits only
                "is_alpha"     - field must only contain alphanumeric characters (0-9, a-Z)
                "custom_alpha" - field must be of the custom format specified.
                      fieldname:  the name of the field
                      fieldname2: a character or sequence of special characters. These characters are:
                          L   An uppercase Letter.          V   An uppercase Vowel.
                          l   A lowercase letter.           v   A lowercase vowel.
                          D   A letter (upper or lower).    F   A vowel (upper or lower).
                          C   An uppercase Consonant.       x   Any number, 0-9.
                          c   A lowercase consonant.        X   Any number, 1-9.
                          E   A consonant (upper or lower).
                "reg_exp"      - field must match the supplied regular expression.  
                      fieldname:  the name of the field
                      fieldname2: the regular expression
                      fieldname3: (optional) flags for the reg exp (like i for case insensitive
                "letters_only" - field must only contains letters (a-Z)

                "length=X"     - field has to be X characters long
                "length=X-Y"   - field has to be between X and Y (inclusive) characters long
                "length>X"     - field has to be greater than X characters long
                "length>=X"    - field has to be greater than or equal to X characters long
                "length<X"     - field has to be less than X characters long
                "length<=X"    - field has to be less than or equal to X characters long

                "valid_email"  - field has to be valid email address
                "valid_date"   - field has to be a valid date
                      fieldname:  MONTH 
                      fieldname2: DAY 
                      fieldname3: YEAR
                      date_flag:  "later_date" / "any_date"
                "same_as"     - fieldname is the same as fieldname2 (for password comparison)

                "range=X-Y"    - field must be a number between the range of X and Y inclusive
                "range>X"      - field must be a number greater than X
                "range>=X"     - field must be a number greater than or equal to X
                "range<X"      - field must be a number less than X
                "range<=X"     - field must be a number less than or equal to X

  
  Comments:   With both digits_only, valid_email and is_alpha options, if the empty string is passed 
              in it won't generate an error, thus allowing validation of non-required fields. So,
              for example, if you want a field to be a valid email address, provide validation for 
              both "required" and "valid_email".
\*--------------------------------------------------------------------------------------------*/
function validateFields($fields, $rules)
{ 
  $errors = array();
  
  // loop through rules
  for ($i=0; $i<count($rules); $i++)
  {
    // split row into component parts 
    $row = explode(",", $rules[$i]);
    
    // while the row begins with "if:..." test the condition. If true, strip the if:..., part and 
    // continue evaluating the rest of the line. Keep repeating this while the line begins with an 
    // if-condition. If it fails any of the conditions, don't bother validating the rest of the line
    $satisfies_if_conditions = true;
    while (preg_match("/^if:/", $row[0]))
    {
      $condition = preg_replace("/^if:/", "", $row[0]);

      // check if it's a = or != test
      $comparison = "equal";
      $parts = array();
      if (preg_match("/!=/", $condition))
      {
        $parts = explode("!=", $condition);
        $comparison = "not_equal";
      }
      else 
        $parts = explode("=", $condition);

      $field_to_check = $parts[0];
      $value_to_check = $parts[1];
      
      // if the VALUE is NOT the same, we don't need to validate this field. Return.
      if ($comparison == "equal" && $fields[$field_to_check] != $value_to_check)
      {
        $satisfies_if_conditions = false;
        break;
      }
      else if ($comparison == "not_equal" && $fields[$field_to_check] == $value_to_check)
      {
        $satisfies_if_conditions = false;
        break;      
      }
      else 
        array_shift($row);    // remove this if-condition from line, and continue validating line
    }

    if (!$satisfies_if_conditions)
      continue;


    $requirement = $row[0];
    $field_name  = $row[1];

    // depending on the validation test, store the incoming strings for use later...
    if (count($row) == 6)        // valid_date
    {
      $field_name2   = $row[2];
      $field_name3   = $row[3];
      $date_flag     = $row[4];
      $error_message = $row[5];
    }
    else if (count($row) == 5)     // reg_exp (WITH flags like g, i, m)
    {
      $field_name2   = $row[2];
      $field_name3   = $row[3];
      $error_message = $row[4];
    }
    else if (count($row) == 4)     // same_as, custom_alpha, reg_exp (without flags like g, i, m)
    {
      $field_name2   = $row[2];
      $error_message = $row[3];
    }
    else
      $error_message = $row[2];    // everything else!


    // if the requirement is "length=...", rename requirement to "length" for switch statement
    if (preg_match("/^length/", $requirement))
    {
      $length_requirements = $requirement;
      $requirement         = "length";
    }

    // if the requirement is "range=...", rename requirement to "range" for switch statement
    if (preg_match("/^range/", $requirement))
    {
      $range_requirements = $requirement;
      $requirement        = "range";
    }


    // now, validate whatever is required of the field
    switch ($requirement)
    {
      case "required":
        if (!isset($fields[$field_name]) || $fields[$field_name] == "")
          $errors[] = $error_message;
        break;

      case "digits_only":       
        if (isset($fields[$field_name]) && preg_match("/\D/", $fields[$field_name]))
          $errors[] = $error_message;
        break;

      case "letters_only": 
        if (isset($fields[$field_name]) && preg_match("/[^a-zA-Z]/", $fields[$field_name]))
          $errors[] = $error_message;
        break;

      // doesn't fail if field is empty
      case "valid_email":
			$regexp="/^[a-z0-9]+([_+\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";    
        if (isset($fields[$field_name]) && !empty($fields[$field_name]) && !preg_match($regexp, $fields[$field_name]))
          $errors[] = $error_message;
        break;

      case "length":
        $comparison_rule = "";
        $rule_string     = "";

        if      (preg_match("/length=/", $length_requirements))
        {
          $comparison_rule = "equal";
          $rule_string = preg_replace("/length=/", "", $length_requirements);
        }
        else if (preg_match("/length>=/", $length_requirements))
        {
          $comparison_rule = "greater_than_or_equal";
          $rule_string = preg_replace("/length>=/", "", $length_requirements);
        }
        else if (preg_match("/length<=/", $length_requirements))
        {
          $comparison_rule = "less_than_or_equal";
          $rule_string = preg_replace("/length<=/", "", $length_requirements);
        }
        else if (preg_match("/length>/", $length_requirements))
        {
          $comparison_rule = "greater_than";
          $rule_string = preg_replace("/length>/", "", $length_requirements);
        }
        else if (preg_match("/length</", $length_requirements))
        {
          $comparison_rule = "less_than";
          $rule_string = preg_replace("/length</", "", $length_requirements);
        }

        switch ($comparison_rule)
        {
          case "greater_than_or_equal":
            if (!(strlen($fields[$field_name]) >= $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than_or_equal":
            if (!(strlen($fields[$field_name]) <= $rule_string))
              $errors[] = $error_message;
            break;
          case "greater_than":
            if (!(strlen($fields[$field_name]) > $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than":
            if (!(strlen($fields[$field_name]) < $rule_string))
              $errors[] = $error_message;
            break;
          case "equal":
            // if the user supplied two length fields, make sure the field is within that range
            if (preg_match("/-/", $rule_string))
            {
              list($start, $end) = explode("-", $rule_string);
              if (strlen($fields[$field_name]) < $start || strlen($fields[$field_name]) > $end)
                $errors[] = $error_message;
            }
            // otherwise, check it's EXACTLY the size the user specified 
            else
            {
              if (strlen($fields[$field_name]) != $rule_string)
                $errors[] = $error_message;
            }     
            break;       
        }
        break;

      case "range":
        $comparison_rule = "";
        $rule_string     = "";

        if      (preg_match("/range=/", $range_requirements))
        {
          $comparison_rule = "equal";
          $rule_string = preg_replace("/range=/", "", $range_requirements);
        }
        else if (preg_match("/range>=/", $range_requirements))
        {
          $comparison_rule = "greater_than_or_equal";
          $rule_string = preg_replace("/range>=/", "", $range_requirements);
        }
        else if (preg_match("/range<=/", $range_requirements))
        {
          $comparison_rule = "less_than_or_equal";
          $rule_string = preg_replace("/range<=/", "", $range_requirements);
        }
        else if (preg_match("/range>/", $range_requirements))
        {
          $comparison_rule = "greater_than";
          $rule_string = preg_replace("/range>/", "", $range_requirements);
        }
        else if (preg_match("/range</", $range_requirements))
        {
          $comparison_rule = "less_than";
          $rule_string = preg_replace("/range</", "", $range_requirements);
        }
        
        switch ($comparison_rule)
        {
          case "greater_than":
            if (!($fields[$field_name] > $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than":
            if (!($fields[$field_name] < $rule_string))
              $errors[] = $error_message;
            break;
          case "greater_than_or_equal":
            if (!($fields[$field_name] >= $rule_string))
              $errors[] = $error_message;
            break;
          case "less_than_or_equal":
            if (!($fields[$field_name] <= $rule_string))
              $errors[] = $error_message;
            break;
          case "equal":
            list($start, $end) = explode("-", $rule_string);

            if (($fields[$field_name] < $start) || ($fields[$field_name] > $end))
              $errors[] = $error_message;
            break;
        }
        break;
        
      case "same_as":
        if ($fields[$field_name] != $fields[$field_name2])
          $errors[] = $error_message;
        break;

      case "valid_date":
        // this is written for future extensibility of isValidDate function to allow 
        // checking for dates BEFORE today, AFTER today, IS today and ANY day.
        $is_later_date = false;
        if    ($date_flag == "later_date")
          $is_later_date = true;
        else if ($date_flag == "any_date")
          $is_later_date = false;

        if (!is_valid_date($fields[$field_name], $fields[$field_name2], $fields[$field_name3], $is_later_date))
          $errors[] = $error_message;
        break;

      case "is_alpha":
        if (preg_match('/[^A-Za-z0-9]/', $fields[$field_name]))
          $errors[] = $error_message; 
        break;
        
      case "custom_alpha":
        $chars = array();
        $chars["L"] = "[A-Z]";
        $chars["V"] = "[AEIOU]";
        $chars["l"] = "[a-z]";
        $chars["v"] = "[aeiou]";
        $chars["D"] = "[a-zA-Z]";
        $chars["F"] = "[aeiouAEIOU]";
        $chars["C"] = "[bCDFGHJKLMNPQRSTVWXYZ]";
        $chars["x"] = "[0-9]";
        $chars["c"] = "[bcdfghjklmnpqrstvwxyz]";
        $chars["X"] = "[1-9]";
        $chars["E"] = "[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]";

        $reg_exp_str = "";
        for ($j=0; $j<strlen($field_name2); $j++)
        {
          if (array_key_exists($field_name2[$j], $chars))
            $reg_exp_str .= $chars[$field_name2[$j]];
          else
            $reg_exp_str .= $field_name2[$j];
        }

        if (!empty($fields[$field_name]) && !preg_match("/$reg_exp_str/", $fields[$field_name]))
          $errors[] = $error_message;
        break;

      case "reg_exp":
        $reg_exp_str = $field_name2;

        // rather crumby, but...
        if (count($row) == 5)
          $reg_exp = "/" . $reg_exp_str . "/" . $row[3]; 
        else
          $reg_exp = "/" . $reg_exp_str . "/"; 

        if (!empty($fields[$field_name]) && !preg_match($reg_exp, $fields[$field_name]))
          $errors[] = $error_message;
        break;

      default:
        die("Unknown requirement flag in validate_fields(): $requirement");
        break;
    }
  }
  
  return $errors;
}


/*------------------------------------------------------------------------------------------------*\
  Function:   is_valid_date
  Purpose:    checks a date is valid / is later than current date
  Parameters: $month       - an integer between 1 and 12
              $day         - an integer between 1 and 31 (depending on month)
              $year        - a 4-digit integer value
              $is_later_date - a boolean value. If true, the function verifies the date being passed 
                               in is LATER than the current date.
\*------------------------------------------------------------------------------------------------*/
function is_valid_date($month, $day, $year, $is_later_date)
{
  // depending on the year, calculate the number of days in the month
  if ($year % 4 == 0)      // LEAP YEAR 
    $days_in_month = array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  else
    $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);


  // first, check the incoming month and year are valid. 
  if (!$month || !$day || !$year) return false;
  if (1 > $month || $month > 12)  return false;
  if ($year < 0)                  return false;
  if (1 > $day || $day > $days_in_month[$month-1]) return false;


  // if required, verify the incoming date is LATER than the current date.
  if ($is_later_date)
  {    
    // get current date
    $today = date("U");
    $date = mktime(0, 0, 0, $month, $day, $year);
    if ($date < $today)
      return false;
  }

  return true;
}

?>

 

 

 

page1.php

<?php
session_start();
$errors = array(); // set the errors array to empty, by default
$fields = array('first_name' => NULL, 'email'=>NULL, 'phone'=>NULL); // stores the field values
$success_message = "";

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,first_name,Enter your name.";
  $rules[] = "required,email,Enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

// Length of field input
  $rules[] = "length=10,phone,Please enter a ten digit Phone number.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    foreach($_POST as $k => $v) {
	$fields[$k] = $v;
}
  }  // no errors! redirect the user to the thankyou page (or whatever)
else
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    $to = "info@site.com";
$subject = "Site Info";
$field_first = strip_tags($_POST['first_name']);
$field_email = strip_tags($_POST['email']);
$field_phone = strip_tags($_POST['phone']);

$body = "Name: $field_first\n Email: $field_email\n Phone: $field_phone\n ";

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
$_SESSION['first_name'] = $field_first;
$_SESSION['email'] = $field_email;
$_SESSION['phone'] = $field_phone;
   header('Status: 200');
   header("Location:customize_search.php");
  }
}
          
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Page title</title>
<meta name="keywords" content="..." />
<meta name="description" content="..." />

<link href="css/style_reset.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/form_style.css" rel="stylesheet" type="text/css" media="screen" />

<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon" />
</head>

<body>
<div id="outer">
  <div class="conleft">
    <div class="conttopad"></div>
    <div class="continner">

    </div><!-- End Content Inner -->
  </div><!-- End Content Left -->
  <div class="conright">
    <div class="conttopad"></div>
    <div class="continner">

<p style=" font-size:13px; text-align:center; line-height:16px">Enter your contact information in the form below…</p>

      <form action="" method="post">
        <fieldset>

<?php

    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:90%;'>Please fix the following errors:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }
?>

            <label for="first_name">Name *
              <input type="text" name="first_name" id="first_name" value="<?php echo $fields['first_name']?>" />
            </label>
            <label for="email">Email *
              <input type="text" name="email" id="email" value="<?php echo $fields['email']?>" />
            </label>
         <label for="phone"><input type="text" name="phone" id="phone" value="<?php echo $fields['phone']?>" /><span style="float:left">Phone *</span><br />
            <span style="font-size:9px; float:left; width:100px;">(Ten digits, no dashes)</span>
             
          </label>
          </fieldset>
    <fieldset style=" clear:both">
            <input class="button" type="image" name="submit" id="submit" value="submit" src="images/send.gif" width="192" height="69" />
            <input type="hidden" name="submit" value="submit" />
          </fieldset>
        </form>
<div style="clear:both"></div>
<p style=" font-size:11px; text-align:center; line-height:16px; color:#737373; clear:left; margin-top:12px"><strong>**Please double-check</strong> that your email address is correct or you won't be able to get all the free training material. I take your privacy
very seriously - your information is NEVER shared.</p>
</div><!-- End Content inner -->
  </div><!-- End Content Right -->
</div><!-- End Outer -->
<div style="clear:both;"></div>
<div id="footer">
<div id="footerinner" style="width:880px">
<div class="conleft" style="width:530px">
</div>
<div class="conright" style="width:350px"></div>
<div style="clear:both;"></div>
</div><!-- End Footer Inner -->
</div><!-- End Footer -->
</body>
</html>

 

customize_search.php

<?php
session_start();
$errors = array(); // set the errors array to empty, by default
$fields = array('first_name' => NULL, 'email'=>NULL, 'last_name'=>NULL, 'phone'=>NULL); // stores the field values
$success_message = "";

if(isset($_SESSION['first_name']) && isset($_SESSION['email']) && isset($_SESSION['phone'])) {
$fields['first_name'] = $_SESSION['first_name'];
$fields['email'] = $_SESSION['email'];
$fields['phone'] = $_SESSION['phone'];
}

if (isset($_POST['submit']))
{
  // import the validation library
  require("validation.php");

  $rules = array(); // stores the validation rules

  // standard form fields
  $rules[] = "required,first_name,Enter your first name.";
  $rules[] = "required,last_name,Enter your last name.";
  $rules[] = "required,email,Enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";

// Length of field input
  $rules[] = "length=10,phone,Please enter a ten digit phone number - No dashes.";

  $errors = validateFields($_POST, $rules);

  // if there were errors, re-populate the form fields
  if (!empty($errors))
  {  
    foreach($_POST as $k => $v) {
	$fields[$k] = $v;
}
  }
  
  // no errors! redirect the user to the thankyou page (or whatever)
  else 
  {
    $message = "All fields have been validated successfully!";
    
    // here you would either email the form contents to someone or store it in a database. 
    // To redirect to a "thankyou" page, you'd just do this:
    $to = "info@site.com";
$subject = "Customized List";
$field_first = strip_tags($_POST['first_name']);
$field_last = strip_tags($_POST['last_name']);
$field_email = strip_tags($_POST['email']);
$field_phone = strip_tags($_POST['phone']);

$body = "First Name: $field_first\n Last Name: $field_last\n Email: $field_email\n Phone: $field_phone\n ";

// Send the mail using PHPs mail() function
mail($to, $subject, $body);
   header('Status: 200');
   header("Location: thank_you.htm");
  }
}
          
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Page Title</title>
<meta name="keywords"..." />
<meta name="description" content="..." />

<link href="css/style_reset.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/form_style_p2.css" rel="stylesheet" type="text/css" media="screen" />

<!--[if lt IE 8]>
   <link rel="stylesheet" type="text/css" href="css/style_ie7.css" />
<![endif]-->

<!--[if lte IE 7]>
   <link rel="stylesheet" type="text/css" href="css/style_ie7.css" />
<![endif]-->

<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon" />
</head>

<body>
<div id="outer">
  <div class="consingle">
    <div class="conttopad" style="background:url(images/topad.gif) no-repeat top center"></div>
    <div class="continner">

<div>
<form id="fm-form" method="post" action="" >
  <h4 id="fm-intro" style="background: #666; color: #FFF">Text</h4>
    <fieldset>
<?php

    // if $errors is not empty, the form must have failed one or more validation 
    // tests. Loop through each and display them on the page for the user
    if (!empty($errors))
    {
      echo "<div class='error' style='width:90%;'>Please fix the following:\n<ul>";
      foreach ($errors as $error)
        echo "<li>$error</li>\n";
    
      echo "</ul></div>"; 
    }
    
    if (!empty($message))
    {
      echo "<div class='notify'>$success_message</div>";
    }
?>

      <label class="fm-req" for="firstname">First name*</label>
        <input class="fm-req" name="first_name" id="first_name" type="text" value="<?php echo $fields['first_name']?>" >
      <label class="fm-req" for="lastname">Last name*</label>
        <input class="fm-req" name="last_name" id="last_name" type="text" value="<?php echo $fields['last_name']?>" >
      <label class="fm-req" for="email">Email*</label>
        <input class="fm-req" id="email" name="email" type="text" value="<?php echo $fields['email']?>" >
      <label class="fm-req" for="phone">Telephone* <span style="font-weight:normal">(10 digits - no dashes)</span></label>
        <input class="fm-req" id="phone" name="phone" title="10-Digit Phone Number, No Dashes" type="text" value="<?php echo $fields['phone']?>">
    </fieldset>

   <div id="sub">
      <input class="fm-req" id="fm-submit" name="submit" value="Send My Info" type="submit">
      <input type="hidden" name="submitted" value="TRUE" >
   </div>
  </form>
</div>

<div style="clear:both"></div>

<div class="conlist">

</div>

    </div><!-- End Content Inner -->
  </div><!-- End Content Single -->
</div><!-- End Outer -->
<div style="clear:both;"></div>
<div id="footer">
<div id="footerinner">
<div class="consingle">

</div>

<div style="clear:both;"></div>
</div><!-- End Footer Inner -->
</div><!-- End Footer -->
</body>
</html>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.