So i am trying to validate a form for php.
my contact form is your typical form
<form method="post" action="contact.php">
<table class="contact">
<tr>
<th>
<label for="name">Name</label>
</th>
<td>
<input type="text" name="name" id="name">
</td>
</tr>
<tr>
<th>
<label for="email">Email</label>
</th>
<td>
<input type="text" name="email" id="email">
</td>
</tr>
<tr>
<th>
<label for="message">Message</label>
</th>
<td>
<textarea name="message" id="message"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Send">
now i want to add the php validation to this so i created the following:
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(empty($name) === true || empty($email) === true || empty($message) === true) {
$errors[] = 'Please fill out all the required forms!';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Sorry please enter a valid email address';
}
if (ctype_alpha($name) === false) {
$errors[] = 'Sorry, name must contain only letters!';
}
}
print_r ($errors);
Now i try to print this out and the array shows the data being imputed into fields, and all the validations work properly. The issue i have is the next step where i add the php to echo out the array in a list.
The code i added above the form was a foreach loop that was suppose to list the error that was shown for any failure of validation:
<?php
if (empty($errors) === false) {
echo '<ul>';
foreach($errors as $error) {
echo '<li>' , $error ,'</li>';
}
echo '</ul>';
}
?>
But now the issue is this: Everytime now i fill out the form the errors don't produce a list they just produce the original array is if the foreach is not being seen.
Any suggestions or help would be great !
thanks guys,
if (count($errors)) echo '<ul><li>'.implode('</li><li>', $errors).'</li></ul>';
else echo 'No errors';
With this are you seeing "No errors"?
Aside, there is no need to do this
if(empty($name) === true)
empty($name) is either true or false. No need to then compare it to true.
if(empty($name))
is perfectly fine, otherwise it's like asking
if ((count(12)>0)==true)!=false)
which would be ridiculous. And actually
if(empty($name.$email.$message))
is far fewer characters, giving the same result as
if(empty($name) === true || empty($email) === true || empty($message) === true)
Related
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
again i trying to do a simple contact form for sending email,
thats the code:
<?php
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
echo $name,' ', $email, ' ', $message;
if (empty($name) === true || empty($email) === true || empty($message) === true) {
$errors[] = 'name,email and message are required';
} else{
if(filter_var($email,FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'that\'s not a valid email address';
}
if(ctype_alpha($name) === false) {
$errors ='name must only contain letters';
}
}
if (empty($errors) ===true) {
mail('talrod160#gmail.com','contact form','$message','From:' . $email);
header('location:index.php?sent');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>A contact form</title>
</head>
<body>
<?php
if (isset($GET ['sent']) === true) {
echo '<p>Thanks for contact us<?/p>';
} else {
if (empty($errors) === false) {
echo '<ul>';
foreach($errors as $error) {
echo '<li>', $error, '</li>';
}
echo '</ul>';
}
?>
<form action="" method="post">
<p>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name" <?php if (isset($_POST['name']) === true){echo ($_POST['name']), '"'} ?>>
</p>
<p>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email"<?php if (isset($_POST['email']) === true){echo 'value="', ($_POST['email']), '"'} ?>>
</p>
<p>
<label for="message">Message:</label><br>
<textarea name="message" id="message"><?php if (isset($_POST['message']) === true) { echo strip_tags ($_POST['message']); } ?></textarea>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
<?php
}
?>
</body>
</html>
now i get this problem and cant understand why,
Parse error: syntax error, unexpected '<' in D:\xampp\htdocs\contact_form\index.php on line 46
and would like if someone can explain me me about foreach loop
thanks.
<p>Thanks for contact us<?/p> probably should be <p>Thanks for contact us</p>
Currently I created registration form. The problem was if I enter the form wrongly, it shows an error message at the top of the form and the form
You can view my full code here
<?php
include 'core/init.php';
logged_in_redirect();
include 'includes/overall/header.php' ;
//if form is being submitted
if(empty($_POST)=== false)
{
//to validate whether user enters smtg or not otherwise no point continue to do the next validation
//create an array
$required_fields = array ('username','password','password_again','first_name','email','passport','gender','contactno','address');
foreach($_POST as $key=>$value)
{
//if the key (value) in array of $required_fields is true which is empty
if(empty($value) && in_array ($key, $required_fields) === true )
{
$errors[] = 'Fields marked with an asterisk are compulsory!';
//the validation can happen to more than 1 field
break 1;
}
}
if(empty($errors) === true)
{
if(user_exists($_POST['username']) === true)
{
$errors[] = 'Sorry, the username \'' .$_POST['username'] . '\' is already taken.';
}
//search for the string, preg_match(search_pattern, your_string)
// \s = white space character
//if(preg_match("/\\s/", $_POST['username']) == true)
if(preg_match("/\s/", $_POST['username']) == true)
{
$errors[] = 'Your username must not contain space.';
}
if(strlen($_POST['password']) < 6)
{
$errors[] = 'Your password must be at least 6 characters';
}
if($_POST['password'] !== $_POST['password_again'])
{
$errors[] = 'Your passwords do not match at all';
}
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false)
{
$errors[] = 'A valid email address is required';
}
if(email_exists($_POST['email']) === true)
{
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.';
}
if(preg_match("/\s/", $_POST['passport']) == true)
{
$errors[] = 'Your passport must not contain space!!.';
}
else if(preg_match("/\s/", $_POST['gender']) == true)
{
$errors[] = 'Your gender must not contain space.';
}
else if (!preg_match('/^[0-9]\d{9}$/', $_POST['contactno']))
{
$errors[] = 'Enter your contact number correctly!!.';
}
}
}
//what does this line does is that to check whether success is in the end of the URL
if(isset($_GET['success']) && empty($_GET['success']))
{
echo 'You have been registered successfully! You may login now';
}
else
{//if there are no errors
if (empty($_POST) === false && empty($errors) === true)
{
//create an array of $register_data for sanitizing purpose ,prevent SQL injection attactk
$register_data = array
(
'username' => $_POST['username'],
'password' => $_POST['password'],
'passport' => $_POST['passport'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'gender' => $_POST['gender'],
'email' => $_POST['email'],
'contactno' => $_POST['contactno'],
'address' => $_POST['address']
);
register_user($register_data);
//redirect and bring success variable to register.php
header('Location: register.php?success');
exit();
}
//
else if (empty($errors) === false)
{
echo output_errors($errors);
}
?>
<form action="" method="post">
<ul>
<li>
Username*:<br>
<input type="text" name="username">
</li>
<li>
Password*:<br>
<input type="password" name="password">
</li>
<li>
Password again*:<br>
<input type="password" name="password_again">
</li>
<li>
<table width="200" border="0">
<tr>
<td width="157" scope="col">First name*: <br>
<input type="text" name="first_name"> </td>
<td width="439" scope="col">Last name: <br>
<input type="text" name="last_name"> </td>
</tr>
<tr>
<td><p>Gender*:
<select name="gender" id="gender">
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</p></td>
<td> </td>
</tr>
<tr>
<td>Passport: <br>
<input type="text" name="passport"></td>
<td> </td>
</tr>
<tr>
<td><p>Email*:<br>
<input type="text" name="email">
</p></td>
<td><p>Contact No*:<br>
<input type="text" name="contactno" id="contactno">
</p></td>
</tr>
<tr>
<td colspan="2"><p>Address*<br>
<input name="address" type="text" size="100">
</p></td>
</tr>
</table>
</li>
<li>
<input type="submit" value="Register">
</li>
</ul>
</form>
<?php
}
include 'includes/overall/footer.php' ; ?>
Now I want to change to show pop up message without reset the form.
Is there any solution to do so?
It will be good if you give form input tags like this :
<input type="text" name="username" placeholder="Username" value="<?php echo $_POST['username']; ?>">
and similarly for other fields except password.
OR
<input type="text" name="username" placeholder="Username" value="<?php echo (isset($_POST['username'])?$_POST['username']:''); ?>">
it will keep your form data if there is some kind of error and you have not validated the form.
PHP is a Server Side processing language. There is no way to process the PHP Code on the client without submitting the form.
However, you can accomplish what you want to using Javascript, which will run client side, and can pop up an alert (or a pop up) to indicate what is wrong with the form before the user submits the form.
There are some great library suggestions, and some great samples of that in this question here: Javascript form validation
Link to website: http://www.leonardpfautsch.com/contact.php
How do I make my contact form validated only using PHP? I want to be able to have error messages directly under the text field that has an error. For each text field, I do not want multiple errors to show up at once. If you submit the form with nothing in the fields, you see that under name and email two errors show up for each. I want the errors to show up only once due to some type of specifications. Right now I think I am on the right track. However, the code below does not have the email being sent. I am very new to PHP. If anybody could help me, I would really appreciate it.
<?php
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))){
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($name === '') {
$name_error_1 = '<div style="color:red;"> Name is a required field! </div>';
}
if ($email === '') {
$email_error_1 = '<div style="color:red;"> Email is a required field! </div>';
}
if ($subject === '') {
$subject_error = '<div style="color:red;"> Subject is a required field! </div>';
}
if ($message === '') {
$message_error = '<div style="color:red;"> Message is a required field! </div>';
}
if (isset($email) && (filter_var($email, FILTER_VALIDATE_EMAIL) === false)){
$email_error_2 = '<div style="color:red;"> The email address must be real! </div>';
}
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
/*Main way that mail works*/
if (empty($errors) === true) {
/*Where_mail_goes_to, Subject, Body_text, Who_email_is_from*/
mail('email_address', $subject, "From " . $name . "\r\r" . $message, 'From: ' . $email);
/*Shows up in the URL if the message has been sent*/
header('Location: contact.php?sent');
exit();
}
} //end of main if
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" >
<span class="label">Name</span><br/>
<?php if (isset($name_error_1)) { echo $name_error_1; } ?>
<?php if (isset($name_error_2)) { echo $name_error_2; } ?>
<input type="text" class="textfield" name="name" size="50" maxlength="50" <?php if (isset($_POST['name']) === true) { echo 'value="', strip_tags($_POST['name']), '"'; } ?> > <br/>
<span class="label">Email</span><br/>
<?php if (isset($email_error_1)) { echo $email_error_1; } ?>
<?php if (isset($email_error_2)) { echo $email_error_2; } ?>
<input type="text" class="textfield" name="email" size="50" maxlength="50" <?php if (isset($_POST['email']) === true) { echo 'value="', strip_tags($_POST['email']), '"'; } ?> > <br/>
<span class="label">Subject</span><br/>
<?php if (isset($subject_error)) { echo $subject_error; } ?>
<input type="text" class="textfield" name="subject" size="50" maxlength="50" <?php if (isset($_POST['subject']) === true) { echo 'value="', strip_tags($_POST['subject']), '"'; } ?> > <br/>
<span class="label">Message</span><br/>
<?php if (isset($message_error)) { echo $message_error; } ?>
<textarea rows="5" cols="50" name="message" id="textarea" maxlength="500"><?php if (isset($_POST['message']) === true){ echo $_POST['message'];}?></textarea><br/>
<input type="submit" value="Send" id="submit" name="action">
</form>
You could create an array of errors for each field and display just the first error added to it.
<?php
$email_errors = array();
if ($email == '')
{
$email_errors[] = 'First error';
}
if (more_email_checks($email) == false)
{
$email_errors[] = 'Second error';
}
?>
...
<span class="label">Email</span><br />
<?php echo array_shift($email_errors); ?>
To know whether to send e-mails or not, you could do something like this:
$errors_found = 0;
if (check_email($email) == false)
{
$email_error = 'Error message';
$errors_found++;
}
...
if ($errors_found == 0)
{
mail(...);
}
You can do it by using the elseif check
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}
elseif(isset($email_error_2)) {
echo $email_error_2;
} ?>
Also move this line after the last validation check
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
you can by this code for name
<?
$message = "<div style = 'color :red ' /> ;
if (isset(name == '' ) {
echo $message
}
?>
this is name php vaildation but yo can create js
Change your email validation to:
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}else if(isset($email_error_2)) {
echo $email_error_2;
} ?>
same if else can be applied to all the fields with multiple validation conditions.
and then move your error array just above the email condition check:
<?php
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
//and change your mail function as:
$to = 'email_address';
$headers = $headers .= 'From: $name <$email>';
mail($to, $subject, $message, $headers);
?>
Also perform a check on the control, if you have filled the form completely then it should come to the mail function, I mean just check the if condition, in case you have some issue with the condition, try to put an echo inside if statement(which is responsible for sending email), and if that echo statement executes then mail should work.
:)
Forgive my noobness coding as I teach myself PHP (lol)!
The code below works almost perfectly for a form I want to create. Whenever the user hits the submit button, provided the form is all filled in correctly, the text "E-mail Sent Successfully" message appears at the top of the page. If any of the mandatory fields are incomplete or invalid, then an error message is returned underneath the corresponding input field and the "e-mail sent successfully" message does not appear. This works properly for all but the last if statement (antispam). Essentially, if you enter the correct answer (3) into the antispam box, then regardless of the other fields being filled in or not, the "e-mail Sent Successfully" message appears (it shouldn't do this as other fields are not filled out correctly). The "e-mail Sent Successfully" message should only appear if all the mandatory fields are completed correctly.
Whatever 'if statement' goes at the bottom adhere's to the same rule (i.e. if name was at the bottom of the if statements, then only name would need to be entered correctly for the e-mail sent successfully message to appear). It feels as though if the last if statement is passed as true, the other statements don't work.
<?php
if (isset($_POST['submit'])) {
$yourname = $_POST['yourname'];
$organisation = $_POST['organisation'];
$email_from = $_POST['email'];
$comments = $_POST['comments'];
$antispam = $_POST['antispam'];
$namestring = "/^[A-Za-z .'-]+$/";
$emailstring = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
$error_message_email = "";
$error_message_name = "";
$error_message_message = "";
$error_message_antispam = "";
if(!preg_match($namestring,$yourname)) {
$error_message_name .= "Please enter a valid name";
}
if(!preg_match($emailstring,$email_from)) {
$error_message_email .= "Please enter a valid e-mail address";
}
if(strlen($comments) < 4) {
$error_message_message .= "Please enter a valid message";
}
if($antispam != "3") {
$error_message_antispam .= "Please enter a valid answer";
}
else {
echo "E-mail Sent Successfully";
}
}
else {
$yourname="";
$organisation="";
$email_from="";
$comments="";
$antispam="";
$error_message_email = "";
$error_message_name = "";
$error_message_message = "";
$error_message_antispam = "";
}
?>
<form name="htmlform" method="post" action="ifandelse.php">
<table width="650px">
<tr>
<td>
<label for="yourname"><font color="#ff0000">*</font>Name:</label>
</td>
<td>
<input type="text" name="yourname" value="<?PHP echo$yourname;?>" maxlength="50" size="40"><br>
<div class="warning">
<?php print $error_message_name;?>
</div>
</td>
</tr>
<tr>
<td>
<label for="organisation">Organisation:</label>
</td>
<td>
<input type="text" name="organisation" value="<?PHP echo$organisation;?>"maxlength="50" size="40">
</td>
</tr>
<tr>
<td>
<label for="email"><font color="#ff0000">*</font>E-mail Address:</label>
</td>
<td>
<input type="text" name="email" value="<?PHP echo$email_from;?>" maxlength="80" size="40"><br>
<div class="warning">
<?php print $error_message_email;?>
</div>
</td>
</tr>
<tr>
<td valign="top">
<label for="comments"><font color="#ff0000">*</font>Message:<br></label>
</td>
<td>
<textarea name="comments" rows="8" cols="60"><?PHP echo$comments;?></textarea><br>
<div class="warning">
<?php print $error_message_message;?>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<font color="#ff0000">*</font>To avoid unwanted spam, please answer the following question correctly: 2 + 1 = <input type="text" name="antispam" value="<?PHP echo$antispam?>" maxlength="100" style="width:30px"><br>
<div class="warning">
<?php print $error_message_antispam;?>
</div>
</td>
</tr>
<tr>
<td>
</td>
<td style="text-align:center;">
<input type="submit" class="formsubmit" name="submit" value="Submit Form">
</td>
</tr>
</table>
</form>
Be most grateful for any help, I've had several friends look into this and we still can't figure out why it's doing this. Have tried nesting the 'if statements' differently, changing the if statement's to else if, etc with no joy :(
I've looked on the forums and can't find a solution that works for me.
You should use a variable to know if there was an error (or more than one) at the end of your verifications. Some code below to give you the general idea :
$isError = false;
if (!preg_match($namestring, $yourname)) {
$error_message_name .= "Please enter a valid name";
$isError = true;
}
if (!preg_match($emailstring, $email_from)) {
$error_message_email .= "Please enter a valid e-mail address";
$isError = true;
}
if (strlen($comments) < 4) {
$error_message_message .= "Please enter a valid message";
$isError = true;
}
if ($antispam != "3") {
$error_message_antispam .= "Please enter a valid answer";
$isError = true;
}
if ($isError) {
//do wathever you have to do
} else {
//send mail
echo "E-mail Sent Successfully";
}
The else statement is attached to you last if and only to this one. Hence, only the last condition matters regarding whether your success message is displayed or not. You'll have to chain your checks :
if (!preg_match($namestring, $yourname)) {
$error_message_name .= "Please enter a valid name";
}
elseif (!preg_match($emailstring, $email_from)) {
$error_message_email .= "Please enter a valid e-mail address";
}
elseif (strlen($comments) < 4) {
$error_message_message .= "Please enter a valid message";
}
elseif ($antispam != "3") {
$error_message_antispam .= "Please enter a valid answer";
} else {
echo "E-mail Sent Successfully";
}
Of course, this will still leave you displaying only one error message at a time, which is far from optimized but that's another matter.
I'm having all kinds of issues with contact form. When I test on my home server everything runs smoothly. Once I upload it online it doesn't work. First there were problems with headers and now apparently "This web page has a redirect loop".
Here's my code. Please advice me what to do.
Thanks.
<?php
// Title: Contact Form - Dolce Forno GB
// Updated: 5/9/2012
//Validation code
if (!empty($_POST)) {
$errors = array();
//variables
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//All field are required
if (empty($name) === true || empty($email) === true || empty($phone) === true || empty($subject) === true || empty($message) === true ){
$errors[] = 'Please fill in all the fields.';
}
else {
//This regex allows only: a-z,A-Z, space, comma, full stop, apostrophe, dash
if (!preg_match("/^[a-zA-Z\s,.'-]+$/", $name)) {
$errors[] = 'Invalid name.';
/*die ("Invalid name."); */
}
//var_filter php function
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Invalid email address.';
}
//This regex allows only: 0-9, space, dash, brackets, min-max length: 10-15
if (!preg_match("/^[0-9\s]{10,15}$/", $phone)){
$errors[] = 'Invalid phone number.';
}
}
}
if (empty($errors)) {
//send email
mail('info#dolcefornogb.com', 'Contact Form', $subject, 'Message:' . $message,'From: ' . $name . $email . $phone);
header('Location:mail.php?sent');
exit ();
}
print_r($errors);
?>
<DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting us!</p>';
}
else {
if (!empty($errors)){
echo '<ul>';
foreach ($errors as $error){
echo '<li>', $error,'</li>';
echo '</ul>';
}
}
?>
<form action="" method="post">
<p> <label for="name">Name
<span class="small">Add your name </span></label>
<input type="text" name="name" id="name"
<?php
if(isset($_POST['name']) === true){
echo 'value="', strip_tags($_POST['name']),'"';
}
?>
>
</p>
<p> <label for="email">E-mail address
<span class="small"> Add your e-mail</span></label>
<input type="text" name="email" id="email"
<?php
if(isset($_POST['email']) === true){
echo 'value="', strip_tags($_POST['email']),'"';
}
?>
>
</p>
<p><label for="phone">Phone<span class="small"> Add your phone number</span></label>
<input type="text" name="phone" id="phone"
<?php
if(isset($_POST['phone']) === true){
echo 'value="', ($_POST['phone']),'"';
}
?>
>
</p>
<p><label for="suject">Subject </label>
<input type="text" name="subject" id="subject"
<?php
if(isset($_POST['subject']) === true){
echo 'value="', strip_tags($_POST['subject']),'"';
}
?>
>
</p>
<p><label for="message">Message:</label>
<textarea name="message" id="messgae" rows="10" cols="50">
<?php
if(isset($_POST['message']) === true){
echo strip_tags($_POST['message']);
}
?></textarea>
</p>
<p><label for="call">Request Phone Call</label>
Yes:<input type="radio" value="Yes" name="call">
No:<input type="radio" value="No" name="call">
</p>
<p class="buttons">
<input type="submit" value="Send"> <input type="reset" value="Clear">
</p>
</form>
<?php
}
?>
Try redirecting to a different page with just the success message in it.
i.e. replace
header('Location:mail.php?sent');
with
header('Location:mail-success.php?sent');
Then get rid of (move to the new page)
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting us!</p>';
}
Also try adding 303 status to the header call
http://www.electrictoolbox.com/php-303-redirect/