I am generating form and handling the submit event in the same file.
If user has not entered the title, I want to display the form again and include an error message (e.g. "You forgot the title.").
That means that I have to duplicate code twice - once to diplay empty form and second to display form with body and ask user to enter title:
<?php if(strlen(strip_tags($_POST['posttitle'])) == 0):
// Display the form with question body that user has entered so far and ask user to enter title.
?>
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
<?php endif;?>
<?php elseif ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action']) && $_POST['action'] == 'post') : ?>
<!-- Everything ok - insert post to DB -->
<?php else :
// just display form here (again ouch!)
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
?>
I would do it like this:
If REQUEST_METHOD is POST I will validate the input and collect messages in an array ($errors in my code).
Then I would just print the form and if there was an error the code will print it.
<?php
$errors = array();
function print_value_for($attr) {
if (isset($_POST[$attr]))
echo $_POST[$attr];
}
function print_error_for($attr) {
global $errors;
if (isset($errors[$attr]))
echo $errors[$attr];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// do validation here and add messages to $errors
// like $errors['posttitle'] = "The title you entered is bad bad bad";
if (empty($errors)) {
// update database and redirect user
}
}
?>
<!-- display the form and print errors if needed -->
<form>
<?php print_error_for('posttitle'); ?>
<input name="posttitle" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postauthor'); ?>
<input name="postauthor" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postbody'); ?>
<textarea name="postbody">
<?php print_value_for('posttitle') ?>
</textarea>
<input type="submit">
</form>
PS. Consider using MVC to separate code and templates.
Here is a quick way to do that.
<form>
<input type="text" name="title" value="<?php echo $_REQUEST['title']; ?>"/>
<input type="text" name="field_a" value="<?php echo $_REQUEST['field_a']; ?>"/>
....
</form>
But I can also advise you to display a var called $title which is the result of a check on $_REQUEST['title].
You could use an output buffer to grab the form and then assign it to a variable like so:
<?php
ob_start();
include('path/to/your/form');
$form = ob_get_flush();
// then later you can just go
print $form;
?>
Hope this helps
When you display the form, use the possibly empty $_POST values as default field values for both the title and question body. If either is empty, the form will display the second time with the other already filled in:
<?php
$message = "";
if (empty($_POST['title'])) $message .= " Please enter a title.";
if (empty($_POST['body'])) $message .= " Please enter a body.";
?>
<form action='me.php'>
<input name='title' type='text' value='<?php if (!empty($_POST['title'])) echo htmlentities($_POST['title'], ENT_QUOTES); ?>' />
<textarea name='body'><?php if (!empty($_POST['body'])) echo $_POST['body']; ?></textarea>
</form>
Read this MVC
Your can write form in view, handler in controller, and business logic in model
Related
I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
I want to display messages at top ids "MessageError" and "MessageOK" according to POST results. Example:
<p id="MessageError"></p>
<p id="MessageOK"></p>
<form name="Form" method="post" action="<?php $_SERVER[ 'PHP_SELF' ]; ?>" enctype="multipart/form-data" accept-charset="UTF-8" id="Form">
<input type="text" name="test" value="" /> <input type="submit" name="Submit" value="" />
</form>
<?php
if ( isset ( $POST[ 'Submit' ] ) ) {
if ( $_POST[ 'test' ] ) {
// Echo message at "MessageOK
}
else {
// "Echo message at "MessageError"
}
}
?>
Any help will be appreciated.
Thank you.
Move the code above your form to print the error message above your form. Also your paragraph tags can be created on the fly, to avoid waste:
<?php
if(isset($_POST['submit'])){
if($_POST['test'])echo("<p id='MessageOk'>There was an Error</p>");
else echo("<p id='MessageError'>There was no error</p>");
}
?>
If you are dead set on adding content to pre-created divs using PHP, can I suggest creating an input using PHP eg:
<?php
$test = $_POST['test'];
echo("<input type='hidden' id='test' value='$test' />");
?>
And then using JavaScript to append data:
if(document.getElementById('test').value){
document.getElementById('MessageOk').innerHTML = 'No Error';
}
else{
document.getElementById('MessageError').innerHTML = 'Error ??';
}
move your php code over the form, assign the echo message to a variable and use <?php echo $variable; ?> to print the message at the appropriate place...
Make sure you include the _ on your post variable.
$_POST[]
My form is working fine with the validations being done by PHP.
I have three fields: Name, EMail and Message.
Form and PHP code is within the same pgae, same page is called for validations when user submits the form.
When a user submits the form, same page is called and it checks whether the form is submitted or not.
If the form is submitted it then does the validations for blank entries and throws error message below the fields to inform user that field is left blank. It also shows error icon next to field.
Till this, it is working fine.
However, the problem, is if the user has filled any field, for example name filed and left the other two fields(EMail and Message) blank, then on submittion, it throws error messages for blank fields which is ok, but for name field which was filled by user it empty the content and shows blank name field and does not show error(as earlier user had filled it).
My only concern is that when it relods the form after submission, it should also reload the earlier values in the respective fields which user input before submitting.
Below is the PHP validation code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST['nameField_Name']) AND isset($_POST['nameField_EMail']) AND isset($_POST['nameField_Message']) AND isset($_POST['nameSubmit'])){
// Form Submited
if ($_POST['nameField_Name']) {
$phpVarNameField = mysql_escape_string($_POST['nameField_Name']);
} else {
$errormsgNameField = "Name field is required, Please enter your Name.";
}
if ($_POST['nameField_EMail']) {
$phpVarEMailField = mysql_escape_string($_POST['nameField_EMail']);
} else {
$errormsgEMailField = "E-Mail field is required, Please enter your E-Mail ID.";
}
if ($_POST['nameField_Message']) {
$phpVarMessageField = mysql_escape_string($_POST['nameField_Message']);
} else {
$errormsgMessageField = "Message field is required, Please enter your Message.";
}
}
?>
Below is the form code.
<form name="myform" action="contactus.php" method="post"">
<div id="r1">
<div id="r1c1">
<input type="text" name="nameField_Name" id="idField_Name" placeholder="Enter your name here"/>
</div>
<div id="r1c2">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr1">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgNameField">'.$errormsgNameField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r2">
<div id="r2c1">
<input name="nameField_EMail" type="text" id="idField_EMail" placeholder="Enter your E-Mail address here" />
</div>
<div id="r2c2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgEMailField">'.$errormsgEMailField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r3">
<div id="r3c1">
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us here"></textarea>
</div>
<div id="r3c2">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 115px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr3">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgMessageField">'.$errormsgMessageField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r4">
<div id="r4c">
<input type="Submit" name="nameSubmit" id="idButton_Submit" value="Submit" alt="Submit Button"/>
</div>
</div>
</form>
Any help will be great on this.
Thank You.
You will need to add a value attribute on your <input> elements:
<input type="text"
name="whatever"
value="<?php echo htmlspecialchars($_POST['whatever']); ?>"
>
It may be easier to read if PHP outputs the field:
<?php
printf('<input type="text" name="%s" value="%s">',
'whatever',
htmlspecialchars($_POST['whatever']));
?>
This can even be wrapped in a function so you don't need to retype it for every single form field.
Note the call to htmlspecialchars. It is needed so that < and > and quotes don't destroy your HTML document.
Try changing your tag like :
<input type="text"
name="nameField_Name"
id="idField_Name"
placeholder="Enter your name here"
value ="<?php
if (isset($phpVarNameField))
echo $phpVarNameField;
?>"
/>
.......
<input
name="nameField_EMail"
type="text"
id="idField_EMail"
placeholder="Enter your E-Mail address here"
value ="<?php if (isset($phpVarEMailField)) echo $phpVarEMailField; ?>"
/>
.......
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us
here" value ="<?php if (isset($phpVarMessageField)) echo $phpVarMessageField; ?>" ></textarea>
Good Luck !
Well, You could do validation with jQuery validation plugin - easy and good. jQuery plugin
Or with PHP store POST data in array, check for errors and fields that are not empty set as value to input text.
if (isset($_POST)) {
$data = $_POST;
}
foreach ($data as $row) {
if ($row == "")
$error = true; // do what ever you want
}
and then in form
<input type="text" name="name" value="<?php ($data['name'] != "")? $data['name'] : '' ?>" />
something like this.
I have a php form that saves the info to my database and sends an email upon completion. however it will not validate the fields to see if they are null, instead it prints both the set and not set options. Any ideas as to why this could be happening? It worked perfectly before i added the form field validation to it.
As a side note it works in FF and Chrome due to the html 5 aria-required, but not in IE
html
<form id="contact" name="contact" action="register1.php" method="post">
<label for='Cname'>Camper Name</label>
<input type="text" name="Cname" maxlength="50" value="" required aria-required=true />
<input type="hidden" id="action" name="action" value="submitform" />
<input type="submit" id="submit" name="submit" value="Continue to Camp Selction"/>
</form>
php
<?php
//include the connection file
require_once('connection.php');
//save the data on the DB and send the email
if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
//recieve the variables
$Cname = $_POST['Cname'];
//form validation (this is where it all breaks)
if (isset($Cname)) {
echo "This var is set so I will print.";
}
else {
echo '<script type="text/javascript">alert("please enter the required fields");</script>';
}
//save the data on the DB (this part works fine)
<?php
$Cname = isset($_POST['Cname']) ? $_POST['Cname'] : null;
if (isset($Cname)) {
echo "This var is set so I will print.";
}
// OR
if (isset($_POST['Cname'])) {
// Perform your database action here...
}
?>
Consider using PHP's empty function
PHP.Net Manual Empty()
You can update your code to the following:
if(!empty($Cname)) {
echo "This var is set so I will print.";
}
Do you just need an "exit()" in the else?
I have an email form that checks three fields, name, valid email and comments. But the way it's set up now, since name and comments are in one function it first checks name and comments even if email is not valid, how can I re-write it so it checks the fields in order. Also, I would like to re-display the fields that have no errors, so the user doesn't have to type again. Please help. Thanks
<?php
$myemail = "comments#myemail.com";
$yourname = check_input($_POST['yourname'], "Enter your name!");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$subject = check_input($_POST['subject']);
$comments = check_input($_POST['comments'], "Write your comments!");
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Enter a valid E-mail address!");
}
exit();
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!doctype html>
<html>
<body>
<form action="myform.php" method="post">
<p style="color: red;"><b>Please correct the following error:</b><br />
<?php echo $myError; ?></p>
<p>Name: <input type="text" name="yourname" /></P>
<P>Email: <input type="text" name="email" /></p>
<P>Phone: <input type="text" name="phone" /></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
exit();
}
?>
First off, I would suggest you validate ALL of the fields at once, and display all appropriate error messages on the form. The primary reason is that it can be bad user experience if they have to submit your form a whole bunch of times because they have to address one error at a time. I'd rather correct my email address, password, comments, and selection in one try instead of fixing one at a time just to reveal what the next error is.
That said, here are some pointers on validating the form like you want. This is typically how I approach a form doing what you want to do. This assumes your form HTML and form processor (PHP) are together in the same file (which is what you have now). You can split the two, but the methods for doing that can be a bit different.
Have one function or code block that outputs the form and is aware of your error messages and has access to the previous form input (if any). Typically, this can be left outside of a function and can be the last block of code in your PHP script.
Set up an array for error messages (e.g. $errors = array()). When this array is empty, you know there were no errors with the submission
Check to see if the form was submitted near the top of your script before the form is output.
If the form was submitted, validate each field one at a time, if a field contained an error, add the error message to the $errors array (e.g. $errors['password'] = 'Passwords must be at least 8 characters long';)
To re-populate the form inputs with the previous values, you have to store the entered values somewhere (you can either just use the $_POST array, or sanitize and assign the $_POST values to individual variables or an array.
Once all the processing is done, you can check for any errors to decide whether the form can be processed at this point, or needs new input from the user.
To do this, I typically do something like if (sizeof($errors) > 0) { // show messages } else { // process form }
If you are re-displaying the form, you simply need to add a value="" attribute to each form element and echo the value that was submitted by the user. It is very important to escape the output using htmlspecialchars() or similar functions
With those things in place, here is some re-work of your form to do that:
<?php
$myemail = "comments#myemail.com";
$errors = array();
$values = array();
$errmsg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST as $key => $value) {
$values[$key] = trim(stripslashes($value)); // basic input filter
}
if (check_input($values['yourname']) == false) {
$errors['yourname'] = 'Enter your name!';
}
if (check_input($values['email']) == false) {
$errors['email'] = 'Please enter your email address.';
} else if (!preg_match('/([\w\-]+\#[\w\-]+\.[\w\-]+)/', $values['email'])) {
$errors['email'] = 'Invalid email address format.';
}
if (check_input($values['comments']) == false) {
$errors['comments'] = 'Write your comments!';
}
if (sizeof($errors) == 0) {
// you can process your for here and redirect or show a success message
$values = array(); // empty values array
echo "Form was OK! Good to process...<br />";
} else {
// one or more errors
foreach($errors as $error) {
$errmsg .= $error . '<br />';
}
}
}
function check_input($input) {
if (strlen($input) == 0) {
return false;
} else {
// TODO: other checks?
return true;
}
}
?>
<!doctype html>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<?php if ($errmsg != ''): ?>
<p style="color: red;"><b>Please correct the following errors:</b><br />
<?php echo $errmsg; ?>
</p>
<?php endif; ?>
<p>Name: <input type="text" name="yourname" value="<?php echo htmlspecialchars(#$values['yourname']) ?>" /></P>
<P>Email: <input type="text" name="email" value="<?php echo htmlspecialchars(#$values['email']) ?>" /></p>
<P>Phone: <input type="text" name="phone" value="<?php echo htmlspecialchars(#$values['phone']) ?>"/></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" value="<?php echo htmlspecialchars(#$values['subject']) ?>" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"><?php echo htmlspecialchars(#$values['comments']) ?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
I have a more advanced example which you can see here that may give you some guidance as well.
Hope that helps.
The simplest option is to use a form validation library. PHP's filter extension, for example, offers validation and sanitization for some types, though it's not a complete solution.
If you insist on implementing it yourself, one issue you'll have to consider is what counts as the order: the order of the elements in the form or the order of the user input in $_POST. On most browsers, these should be the same, but there's no standard that enforces this. If you want to go off of form order, you'll need to define the form structure in one place, and use that information to do things like generating or validating the form (a consequence of the Don't Repeat Yourself (DRY) principle). Iterating over the appropriate structure will give you the order you desire: looping over the form gives you form order, whereas looping over $_POST gives you user input order.
It looks like you want to more than simply validate the data; you also want to prepare it for use, a process called "sanitization".
When it comes to sanitization, define different kinds of sanitizers, rather than a single check_input function. Specific sanitizers could be functions, or objects with an __invoke method. Create a map of form fields to sanitizers (for example, an array of input name to sanitizer callbacks). The order of the elements in the mapping sets the order of the sanitization; if you use a single structure to define the form information, the display order and sanitization order will thus be the same.
Here's a very broad outline:
# $fields could be form structure or user input
foreach ($fields as $name => $data) {
# sanitize dispatches to the appropriate sanitizer for the given field name
$form->sanitize($name, $data);
# or:
//sanitize($name, $data);
# or however you choose to structure your sanitization dispatch mechanism
}
As for setting an input's value to the user-supplied data, simply output the element value when outputting the element. As with all user input (really, all formatted output), properly escape the data when outputting it. For HTML attributes, this means using (e.g.) htmlspecialchars. Note you should only escape outgoing data. This means your sanitization functions shouldn't call htmlspecialchars.
You can improve usability by placing each error next to the corresponding input, adding an "error" class to the element and styling the "error" class to make it stand out. Improve accessibility by wrapping <label> elements around the label text.
Use this structure of script:
<?php
$errors = array();
if (isset($_POST['send'])) {
// check data validity
if (!mailValid($_POST['email']))
$errors[] = 'Mail is not valid';
...
// send data by email
if (!$errors) {
// send mail and redirect
}
}
?>
<html>
...
<?php
if ($errors) {
// display errors
foreach ($errors as $error) {
echo "$error<br />";
}
}
?>
<form ...>
...
Email: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '' ?>" />
...
</form>
...
</html>
You could always do it like this, using filter_var and in_array checks:
<?php
$myemail = "comments#myemail.com";
//Pre made errors array
$errors=array('name'=>'Enter Your name',
'email'=>'Please enter valid email',
'phone'=>'Please enter valid phone number',
'subject'=>'Please enter valid subject, more then 10 chars',
'comment'=>'Please enter valid comment, more then 10 chars');
//Allowed post params and its validation type
$types = array('name'=>'string',
'email'=>'email',
'phone'=>'phone',
'subject'=>'string',
'comment'=>'string');
//A simple validation function using filter_var
function validate($value,$type){
switch ($type){
case "email":
return ((filter_var($value, FILTER_VALIDATE_EMAIL))?true:false);
break;
case "phone":
return ((preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $value))?true:false);
break;
case "string":
return ((strlen($value) >=10 )?true:false);
break;
default:
return false;
break;
}
}
//If forms been posted
if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
//Assign true, if all is good then this will still be true
$cont=true;
$error=array();
foreach($_POST as $key=>$value){
//if key is in $types array
if(in_array($key,$types)){
//If validation true
if(validate($value, $types[$key])==true){
$$key=filter_var($value, FILTER_SANITIZE_STRING);
}else{
//Validation failed assign error and swithc cont to false
$error[$key]=$errors[$key];
$cont=false;
}
}
}
}
if($cont==true && empty($error)){
//Send mail / do insert ect
}else{
//Default to form
?>
<!doctype html>
<html>
<body>
<form action="" method="post">
<p>Name: <input type="text" name="name" value="<?=#htmlentities($name);?>"/> <?=#$error['name'];?></P>
<P>Email: <input type="text" name="email" value="<?=#htmlentities($email);?>" /> <?=#$error['email'];?></p>
<P>Phone: <input type="text" name="phone" value="<?=#htmlentities($phone);?>"/> <?=#$error['phone'];?></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /> <?=#$error['subject'];?></p>
<p>Comments: <?=#$error['comment'];?><br />
<textarea name="comment" rows="10" cols="50" style="width: 100%;"><?=#htmlentities($comment);?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
}?>