Problems with contact form functionality in php - php

Before You read the code, I have tried separating each part into their own php files and just using requires to fetch the code, but using requires or having all the code in the same file I seem to be getting the same errors regardless. I think it may have something to do with the the version of PHP I'm using.
I seem to be getting an error with submit on line 3 of the BACKEND part. Being an undefined property.
The second is an undefined error on the USER FEEDBACK section.
I've used this template before and has worked successfully.
I'm running PHP 5.4.12 and Apache 2.4.4 using WAMP on my Windows 8.1 Pro PC.
Any help would be appreciated
/** BACKEND **/
<?php
if($_POST['submit'])
{
$fName=$_POST['fName'];
$topic=$_POST['topic'];
$email=$_POST['email'];
$message=$_POST['message'];
function verify_email($email)
{
if(!preg_match('/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*#[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',$email))
{
return false;
}
else
{
return $email;
}
}
function verify_email_dns($email)
{
list($name, $domain) = split('#',$email);
if(!checkdnsrr($domain,'MX'))
{
return false;
}
else
{
return $email;
}
}
if(verify_email($email))
{
if(verify_email_dns($email))
{
if ($fName=='')
{
header('location:./contact.php?error=missing');
}
elseif ($email=='')
{
header('location:./contact.php?error=missing');
}
elseif ($message=='')
{
header('location:./contact.php?error=missing');
}
else
{
foreach ($myvars as $var)
{
if (isset($_POST[$var]))
{
$var=$_POST[$var];
}
}
$subject = "Email Submission for review";
$add.="test.email#gmail.com";
$msg.="First Name: \t$fName\n";
$msg.="Email: \t$email\n";
$msg.="Topic: \t$topic\n";
$msg.="Message: \t$message\n";
$mailheaders="From: $email\n";
$mailheaders.="Reply-To: $email\n";
mail("$add", "$subject", $msg, $mailheaders);
header('location:./contact.php?error=none');
}//end else
}//end inner-if
else
{
header('location:./contact.php?error=mx');
}
}// end outter-if
else
{
header('location:./contact.php?error=format');
}
}// end starting if
/** VIEW for form **/
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
<label for="fName" class="first-name">Name:</label>
<input type="text" name="fName" value="" id="fName">
<br><br>
<label for="email" class="email-name">Email:</label>
<input type="text" name="email" value="" id="email">
<br><br>
<label for="topic" class="subject-name">Subject:</label>
<input type="text" name="topic" value="" id="topicsubject">
<br><br>
<label for="message" class="message-name">Message:</label>
<textarea name="message" rows="5" cols="60" id="message"></textarea>
<br><br>
<input type="submit" name="submit" id="submit-btn" class="submit-btn" value="Email Me">
</form>
/** USER FEEDBACK if error occurs **/
<?php
$error=$_GET['error'];
switch ($error)
{
case "mx":
echo "<br><span class='red'>Your email address you entered is invalid. Please try again.</span><br>";
break;
case "format":
echo "<br><span class='red'>Your email address is not in the correct format, it should look like name#domain.com. Please try again.</span><br>";
break;
case "missing":
echo "<br><span class='red'>You seem to be missing a required field, please try again.</span><br>";
break;
case "none":
echo "<br>Your email was sent. I will get back to you as soon as I can. Thank you for your interest.<br>";
break;
default:
echo "<br><br>";
}
?>

You are assuming that there are POST and GET variables when you are visiting the page. So its possible that $_POST['submit'] only exists when you actually submit the form otherwise you will get an error when first visiting that page.
try this condition instead:
if(isset($_POST['submit']) ) {
// now its safe to do something
}
You should never assume that any $_POST or $_GET variable is available when visiting the page.
Also off topic:
In your HTML you are using an 'action' attribute with the same url as the page you are visiting on this line here:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactForm">
Basically if you just leave out the action attribute all together it will have the same effect and its also semantic to do so. This is a better way of doing it and it has the same effect:
<form method="post" name="contactForm">
You can check this previous Stack Overflow question for a better explanation on that matter:
Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

Related

How to pass and put variable from a php page into a another page(form)?

I working on two pages, a first one which has a form with three fields: name, email and message). This page will send these data to a second page, that will validate if those fields meet the criteria.
If on the second page, any of those fields does not meet the criteria, I want to redirect to the first page (or a third php one), fill the form with previous information and tell the user to correct the fields properly.
I'm strugling to send the data form the second page to the first (or third) one. Does anyone knows a good way to do it?
Here's my code:
First page - contato.html
<form action="validate.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" id="name" name="nome" placeholder="Type your name">
</div>
<div class="form-group">
<input type="text" id="email" name="email" placeholder="type your#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="Leave your message." ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send message" onclick="alert('Thank you!')" ></form>
Second Page - validate.php
if(isset($_POST['nome'])) $nome = $_POST['nome'];
if(isset($_POST['email'])) $email_visitante = $_POST['email'];
if(isset($_POST['mensagem'])) $mensagem = $_POST['mensagem'];
// if does not meet the criteria, redirect to contato.html and update the form with the info
if(empty($nome)){
Header("location:contato.html");
}
if(empty($email_visitante)){
Header("location:contato.html");
}
if(empty($mensagem)){
Header("location:contato.html");
}
// check for letters and space only
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
Header("location:contato.html");
}
// check if e-mail address is well-formed
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
Header("location:contato.php");
}
Does anyone knows how to do it? Either sending to a third page or redirecting to the first one (and fill the form in again)
You have to use sessions and store data there in one page and access in another, here is a small usage
<?php
// page 1
session_start();
// Set session variables
$_SESSION["nome"] = $nome;
$_SESSION["email"] = $email_visitante;
$_SESSION["mensagem"] = $mensagem;
<?php
// page 2|3|N - any other page
session_start();
// Get session variables
$nome = $_SESSION["nome"];
$email_visitante = $_SESSION["email"];
$mensagem = $_SESSION["mensagem"];
Part of your problem is that upon any failed validation you are using a redirect. Alternatively you can display an error message to the user: suggesting they need to correct their input by going back a page (browser back).
When forms get longer users need some hand holding with error correction. Their errors need to be clearly indicated with a message alongside as to how they can fix it.
Avoiding using the 'browser back' method above it's common to have the form send to its own url. I've included an example below.
By doing this you can repopulate the form with posted values upon error and add error feedback. You must be careful to escape user input in this situation.
I've added a generic error feedback notice. Which isn't that helpful in its current form. You could improve upon this by adjusting the validation code to return an array of error notices and use that within your form for more targeted error feedback. You could also add - all fields are required - text to help the user.
Upon successful validation that's when to redirect the user to a confirmation page. This can prevent form resubmissions.
Your name regex pattern in its current form will not allow hyphens or apostrophes. I haven't changed it below. Do bear this in mind. "Michael O'leary" would be faced with an error and likely not understand why. You need to be careful when using strict rules for user input. Also this will reject some unicode.
You also need to escape user input appropriately. Note that you may be satisfied that the name and email after validation follows a particular pattern, but becareful of raw user input. The message text is passed on raw after validation.
<?php
$nome = $_POST['nome'] ?? null;
$email_visitante = $_POST['email'] ?? null;
$mensagem = $_POST['mensagem'] ?? null;
$feedback = null;
if(isset($_POST['submit'])) {
if(validate($nome, $email_visitante, $mensagem) !== false) {
process($nome, $email_visitante, $mensagem);
// Redirect to success/thankyou/confirmation page.
header('location:success.html');
exit;
}
// This is a generic message, could this be more helpful?
$feedback = 'Your form has errors. Please correct them.';
}
form($nome, $email_visitante, $mensagem, $feedback);
function process($nome, $email_visitante, $mensagem) {
// do something with your values.
}
function validate($nome, $email_visitante, $mensagem) {
if(empty($nome)) {
return false;
}
if(empty($email_visitante)){
return false;
}
if(empty($mensagem)){
return false;
}
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
return false;
}
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
function form($nome = null, $email_visitante = null, $mensagem = null, $feedback = null) {
?>
<?= $feedback ?>
<form action='' method='POST' name='emailform'>
<div class='form-group'>
<label for='name'>Your name:</label>
<input type='text' id='name' name='nome' value='<?= htmlspecialchars($nome) ?>'>
</div>
<div class='form-group'>
<label for='email'>Your email address:</label>
<input type='text' id='email' name='email' value='<?= htmlspecialchars($email_visitante) ?>'>
</div>
<div class='form-group'>
<label for='message'>Your message:</label>
<textarea class='form-control' cols='30' rows='10' maxlength='300' id='message' name='mensagem'><?= htmlspecialchars($mensagem) ?></textarea>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Send message'>
</div>
</form>
<?php
}

php validation removes the data from html input

I'm having some problem with html input validation using PHP. The validation itself is working. I have two inputs: name and office.
If I enter a value on Name input but i didn't put value to the office input and click the submit button, the validation on office input works but it CLEAR/null the data i entered on name input
What am I doing wrong here?
This is my PHP validation:
if (isset($_POST['submit'])){
$signatory_name = $_POST['sig_name'];
$signtory_position = $_POST['sig_position'];
if (!$_POST['sig_name']) {
$errname='<div class="alert alert-danger">Sorry there was an error: Please Enter Your Name</div>';
}
if (!$_POST['sig_office']) {
$erroffice='<div class="alert alert-danger">Sorry there was an error: Please Enter Your office</div>';
}
}
this is my html code
<form action="signatory.php" method="Post" role="form">
<input class="form-control " id="signatoryname" name="sig_name" placeholder="Name:" >
<input class="form-control " id="signatoryoffice" name="sig_office" placeholder="Office:">
</form>
It's not really clear what you are doing or trying to do but here is my attempt:
First: You should know that if (!$_POST['sig_name']) { means if the value assigned is FALSE you may want to reconsider this and use empty() instead.
After validating the inputs you need to repopulate the form with the submitted values - here is an example:
<?php
$errname = "";
$erroffice= "";
if (!empty($_POST)) { // Only if there are POST values attached.
$signatory_name = $_POST['sig_name'];
$signtory_position = $_POST['sig_position'];
if (empty($_POST['sig_name'])) {
$errname='<div class="alert alert-danger">Sorry there was an error: Please Enter youre Name</div>';
}
if (empty($_POST['sig_office'])) {
$erroffice='<div class="alert alert-danger">Sorry there was an error: Please Enter youre office</div>';
}
if (empty($errname) && empty($erroffice)) {
//Do whatever you need with the validated inputs...
} else {
//Expose the alerts:
echo $errname.$erroffice;
}
}
?>
<form method="POST" role="form">
<input class="form-control" id="signatoryname" name="sig_name" value="<?php echo (isset($_POST['sig_name']))?$_POST['sig_name']:""; ?>" placeholder="Name:" />
<input class="form-control" id="signatoryoffice" name="sig_office" value="<?php echo (isset($_POST['sig_office']))?$_POST['sig_office']:""; ?>" placeholder="Office:" />
<!-- rest of your form and buttons -->
</form>
You need to re-populate your form as Scuzzy said.
Most browsers might do you for you, but you can't rely on it.
<form action="signatory.php" method="Post" role="form">
<input class="form-control " id="signatoryname" name="sig_name" placeholder="Name:" value="<?php echo !empty($_POST['sig_name']) ? $_POST['sig_name'] : ''; ?>">
<input class="form-control " id="signatoryoffice" name="sig_office" placeholder="Office:" value="<?php echo !empty($_POST['sig_office']) ? $_POST['sig_office'] : ''; ?>">
</form>

PHP: Refresh page on invalid form submit

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}

php form validation issues - cannot print to header

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?

PHP Show error messages in order and re-display correct fields

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
}?>

Categories