PHP Feedback form Checkbox error - php

Ok here is a shortened version of the php for my contact form, (the checkboxes are not being sent through correctly)
<?php
//please fill this in at least!
$myemail = "";
$title = "Feedback Form";
if(isset($_POST['submit'])) { //form has been submitted
//set variables with filters
$cont_name = filter_var($_POST['cont_name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['cont_email'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['cont_phone'], FILTER_SANITIZE_STRING);
$first_time = filter_var($_POST['first_time'], FILTER_SANITIZE_STRING);
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
function valid_email($str){
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;}
$errors = 0; //by default there are no errors
$trimcont_name = trim($cont_name);
if(empty($trimcont_name)){
//the name field is empty
$errors = 1; //tips off the error messages below
$errorcont_name = "The name field is empty"; //this error is displayed next to the label
}
if(!valid_email($email)) {
//email is invalid or empty
$errors = 1;
$erroremail = "The email address was not valid";
}
$trimphone = trim($phone);
if(empty($trimphone)){
//the phone field is empty
$errors = 1;
$errorphone = "The phone field is empty";
}
$trimfirst_time = trim($first_time);
if(empty($trimfirst_time)){
//the first_time field is empty
$errors = 1;
$errorfirst_time = "This field is empty";
}
$trimhear_about = trim($hear_about);
if(empty($trimhear_about)){
//the hear_about field is empty
$errors = 1;
$errorhear_about = "This field is empty";
}
if($spam != "") {
//spam was filled in
$errors = 1;
$errorspam = "The Spam box was filled in";
}
if($errors == 0) {
$sendto = $myemail;
$message = <<<DATA
DETAILS
Name: $cont_name
Email: $email
Phone: $phone
Was this the first time you have been to us?
$first_time
How did you hear about us?
$hear_about
DATA;
$headers = 'From: ' . $name . '<' . $email . '>';
if(mail($sendto, $title, $message, $headers)) {
//this is where it sends, using the php mail function
$success = true;
//set all the variables to blank to prevent re-submitting.
$cont_name = "";
$email = "";
$phone = "";
$hear_about = "";
$first_time = "";
} else {
$success = false;
}
} else {
$success = false;
}
}
?>
And the area not functioning correctly is
<fieldset>
<legend>How did you hear about us? <span class="phpformerror"><?php echo $errorhear_about; ?></span></legend>
<div><input type="checkbox" name="hear_about[]" value="Web" /> Web</div>
<div><input type="checkbox" name="hear_about[]" value="Newspaper" /> Newspaper</div>
<div><input type="checkbox" name="hear_about[]" value="Radio" /> Radio</div>
<div><input type="checkbox" name="hear_about[]" value="Driving" /> Driving Past</div>
<div><input type="checkbox" name="hear_about[]" value="Referal" /> Referal</div>
<div><input type="checkbox" name="hear_about[]" value="Other" /> Other</div>
</fieldset>
At the moment it will only come through displaying one of the variables if multiple variables are selected.

hear_about is an array and filter_var() does not handle arrays correctly. Instead use filter_var_array():
$hear_about = filter_var_array($_POST['hear_about'], FILTER_SANITIZE_STRING);
Remember that $hear_about is an array, and must be treated like one throughout your code (e.g. just using $hear_about won't work, it needs to be $hear_about[0], $hear_about[1], etc).
So for example in your trim line you would need something like:
foreach($hear_about as $key => $value) {
$trimhear_about[$key] = trim($value);
if(empty($trimhear_about[$key])){
//the hear_about field is empty
$errors = 1;
$errorhear_about[$key] = "This field is empty";
}
}
This will preserve the benefits of dealing with an array.

$_POST['hear_about'] is an array of values. You are handling it as a simple string!
I think you can solve simply replacing the line:
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
With:
$hear_about = filter_var(implode(', ', $_POST['hear_about']), FILTER_SANITIZE_STRING);
The implode function (doc) "transform" an array to a string by concatenating the array values with the given glue. So you can just concatenate selected "How did you hear about us?" options with a comma and then use the resulting string as the other data.

Related

Submit PHP form to different addresses dependant on option selected from dropdown

How can I submit a form to one of 4 different addresses depending on what the user selects from a dropdown?
So 4 options are 1,2,3,4 (in my case these are different branches) If 1 is selected I want the form to submit to 1#email.com, if 2 is selected the form should go to 2#email.com etc.
I saw similar questions on here but always seem to be database or wordpress related.
The processor for the form looks like this:
<?php
include_once "includes/funcs.php";
$success=$_GET['success'];
if(isset($_POST['submit']))
{
/* Check all form inputs using check_input function */
$name = trim(stripslashes(htmlspecialchars($_POST['InputName'])));
$email = trim(stripslashes(htmlspecialchars($_POST['InputEmail'])));
$phone = trim(stripslashes(htmlspecialchars($_POST['InputPhone'])));
$branch = trim(stripslashes(htmlspecialchars($_POST['InputBranch'])));
$message = trim(stripslashes(htmlspecialchars($_POST['InputMessage'])));
$j=0;
$filecount=count($_FILES['upload']['name']);
for($i=0; $i<$filecount; $i++)
{
//Get the temp file path
//Make sure we have a filepath
if ($_FILES['upload']['size'][$i]<=2048000){
$filep[$j]=$_FILES['upload']['tmp_name'][$i];
$filen[$j]=$_FILES['upload']['name'][$i];
$j+=1;
//echo $files[$i]."<br/><br/>";
}
}
$subject = "You have received an enquiry";
$message = "
This is a message via the website:
Name: $name
Email: $email
Subject: $subject
Telephone: $phone
Branch: $branch
Message:
$message
";
//echo "here";
/* Send the message using mail() function */
emailPerson($subject,$message,'xx#emailaddress.com',$filep,$filen);
/* Redirect visitor to the thank you page */
$success=1;
$name = "";
$email = "";
$phone = "";
$branch = "";
$message = "";
header('Location: thanks-for-your-interest.php');
//exit();
}
include_once "includes/top.php";
?>
and the HTML:
<label for="InputBranch">Please select the branch you wish to send this message to:</label>
<div class="input-group">
<select class="form-control" name='InputBranch' id='InputBranch' required >
<option value="Branch 1">1</option>
<option value="Branch 2">2</option>
<option value="Branch 3">3</option>
<option value="Branch 4">4</option>
</select>
<span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span></div>
</div>
Currently the logic tells it to submit to xx#emailaddress.com each time and just picks up the name of the branch in the email but I need it to go to the relevant branch.
Thanks
Simple: just check what the value POSTed was for your input. In your case, it’s called InputBranch:
switch ($_POST['InputBranch']) {
case 'Blackpool':
$email = 'blackpool#exmaple.com';
break;
case 'Kendal':
$email = 'kendal#exmaple.com';
break;
case 'Lancaster':
$email = 'lancaster#exmaple.com';
break;
case 'Preston':
$email = 'preston#exmaple.com';
break;
default:
throw new Exception('Invalid branch selected.')
}
mail($email, $subject, $message, $headers);
Also, you don’t need to reset variables here:
$success=1;
$name = "";
$email = "";
$phone = "";
$branch = "";
$message = "";
header('Location: thanks-for-your-interest.php');
If you’re just going to redirect. The variables’ values won’t persist between pages.
You could do:
<?php
$recipients = array(
'Branch 1' => 'email1#domain.com',
'Branch 2' => 'email2#domain.com',
'Branch 3' => 'email3#domain.com',
'Branch 4' => 'email4#domain.com',
);
if (isset($recipients[$branch])) {
$to = $recipients[$branch];
} else {
// invalid branch selected
}
You could put this after you assign the variables from $_POST and it will select the recipient from the array based on the submitted form value.

PHP Simple Form Validation

Ok, what I'm trying to achieve is a very simple form validation like the following.
Name: [required, min length: 2, max length: 255]
Email: [required, min length: 3, max length: 255, valid email format]
Date of Birth: [optional, format: dd/mm/yyyy]
However, once i click submit (either if the fields are empty or filled) I get all of my echoed errors displayed on a blank page.
"name must be at least 2 charactersname is requiredemail must be at least 3 charactersinvalid emailemail cannot be left empty"
My code so far:
index.php
<form method="post" action="confirm.php">
Name:<input type="text" name="name" />
email:<input type="text" name="email" />
DOB:<input type="date" name="dob" />
<input type="submit" value="submit" />
</form>
and
confirm.php
<?php
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
$namelen = strlen($email);
$emaillen = strlen($email);
$max = 255;
$minname = 2;
$minemail = 3;
if($namelen<$minname){
echo"name must be at least 2 characters";
}
elseif($namelen>$max){
echo"name must be less than 255 characters";
}
if(empty($name)){
echo"name is required";
}
else{
continue;
}
if($emaillen<$minemail){
echo"email must be at least 3 characters";
}
elseif($emaillen>$max){
echo"email must be less than 255 characters";
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
continue;
}
else{
echo"invalid email";
}
if(empty($email)){
echo"email cannot be left empty";
}
else{
continue;
}
?>
Help would be greatly appreciated, thank you.
You have the following in your code:
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
You're basically trying to access undefined indexes. Remove the extra $ from the key names:
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
Then, further below, you have some conditions like this:
if(condition == true) {
continue;
} else {
// do something
}
It's actually not necessary, and you could change it to:
if(!condition) {
// do something
}
Also, it's better to push the error messages into an array ($errors) and then loop through it and display the error messages. It might help organize your code a bit better.
Here's how the modified code looks like:
if(!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$namelen = strlen($name);
$emaillen = strlen($email);
$max = 255;
$minname = 2;
$minemail = 3;
if($namelen < $minname){
$errors[] = "name must be at least 2 characters";
} elseif($namelen > $max){
$errors[] = "name must be less than 255 characters";
}
if($emaillen < $minemail){
$errors[] = "email must be at least 3 characters";
} elseif($emaillen > $max){
$errors[] = "email must be less than 255 characters";
}
if(empty($name)){
$errors[] = "name is required";
}
if(empty($email)){
$errors[] = "email cannot be left empty";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "invalid email";
}
echo "<ul>";
foreach ($errors as $error) {
echo "<li>$error</li>";
}
echo "</ul>";
}
It could still be improved, but however, this should get you started!
You have not written anything to make it stop after checking the first and second error.
Also, continue makes no sense in an if statement (see http://php.net/manual/en/control-structures.continue.php).
Lastly, the page is "blank" because there is no HTML output, just the text. You might want to redirect the user back to the form page with the error messages instead.
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
That's wrong, you have to use
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
Also you may want to change the line
$namelen = strlen($email);
to
$namelen = strlen($name);
check if(!empty($_POST[fieldname]))
and then redirected it displaying a alert in javascript that the fields are empty

Select case with array

How can I write a select case with an array to check form validation?
this is my code:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
switch($array[]) {
case empty($array[0]):
error = "name";
break;
case empty($array[1]):
error = "email";
break;
case empty($array[2]):
error = "message";
}
Then, I would like to write code to have this result:
if name is empty:
"Please fill in your name"
if email is empty:
"Please fill in your email"
if name and email is empty:
"Please fill your name and email"
if name and email and message is empty:
"Please fill in your name, email and message"
You want to concat your messages, so better use if statements:
$error = "Please fill in: ";
if (empty($array[0]))
$error .= "name ";
if (empty($array[1]))
$error .= "email ";
if (empty($array[2]))
$error .= "message ";
The .= will concat the string to the existing one.
Try this for a grammatically correct solution:
$empty = array();
$fields = array('name', 'email', 'message');
foreach ($fields as $key => $value){
if(empty($_POST[$value])) $empty[] = $value;
}
$error_msg = '';
$count = count($empty);
$cnct = ', ';
if ($count > 0){
$error_msg = 'Please fill in your ';
}
foreach ($empty as $key => $value){
if ($key == $count - 2){
$cnct = ' and ';
}elseif($key == $count - 1){
$cnct = '.';
}
$error_msg .= $value.$cnct;
}
You can simply try:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$error="Please fill in your ";
$array = array('name'=>$name,'email'=>$email,'message'=>$message);
foreach($array as $key=>$value){
if(empty($value)){
$error.=','.$key;
}
}
You can't use a variable expression in case statement of switch block.
A switch case must have a constant expression in many languages including php. So, something like a variable or function call doesn't work.
You better use conditionals for this.
Your code is also missing $ symbol for variable error.
Do this instead:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
$error="Please fill in your ";
if(empty($array[0])){
$error.= "\nname";
}
if(empty($array[1])){
$error.="\nemail";
};
if(empty($array[2])){
$error.= "\nmessage";
}
echo $error;
You should simply write:
$error = "Please fill in: ";
if (empty($array[0]))
$error.= "name ";
if (empty($array[1]))
$error.= "email ";
if (empty($array[2]))
$error.= "message";
A switch isn't made for what you want to do.

Checkbox value not displaying

The form inputs aren't displaying on the form.php page and negates my form validation. The error says undefined variable for all my variables on form.php. Please tell me what I have to edit in my code to make it display the form inputs on form.php. It works when I use it on the same page but I would rather it display on another page.
EDIT
Thanks so far but I can't get the value of the checkbox, the recipient(Administrator or Content Editor), to display it displays "Array" or "A".
contact.php
<?php
$errnam = "";
$errmail = "";
$errsub = "";
$errrec = "";
$hasErrors = false;
if(isset ($_POST['submitted'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$recipient = $_POST['recipient'];
$message = $_POST['message'];
if(preg_match("/^[\w\-'\s]/", $_POST['name'])){
$name = $_POST['name'];
}
else{
$errnam ='<strong>Please enter a name.</strong>';
$hasErrors = true;
}
if (preg_match("/^[\w.-_]+#[\w.-]+[A-Za-z]{2,6}$/i", $email)){
$email = $_POST['email'];
}
else{
$errmail = '<strong>Please enter a valid email.</strong>';
$hasErrors = true;
}
if(preg_match("/^[\w\-'\s]/", $_POST['subject'])){
$subject = $_POST['subject'];
}
else{
$errsub = "<strong>Please enter a subject.</strong>";
$hasErrors = true;
}
if (!empty($_POST['recipient'])) {
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'];
}
}else{
$errrec = "<strong>Please select a recipient</strong>";
$hasErrors = true;
}
$message = $_POST['message'];
}
if ($hasErrors){
echo "<strong>Error! Please fix the errors as stated.</strong>";
}else{
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject. "&recipient=".$recipient. "&message=".$message);
exit();
}
?>
form.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$recipient = $_GET['recipient'];
$message = $_GET['message'];
echo "<h2>Thank You</h2>";
echo "<p>Thank you for your submission. Here is a copy of the details that you have sent.</p>";
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong>" .$recipient. "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
?>
If you would like to transfer the data from contact.php to form.php you should use something like this:
contact.php
$data = urlencode(
serialize(
array(
"name" => $name,
"email" => $email,
"subject" => $subject,
"message" => $message)
));
header('Location: form.php?data=' . $data);
form.php
$data = unserialize(urldecode($_GET['data']));
$name = $data["name"];
$email = $data["email"];
$subject = $data["subject"];
$message = $data["message"];
This serializes the array of data from contact.php then URL encodes it and sends it as a GET variable to form.php. After, form.php URL decodes and unserializes the data for use.
The problem is when you header("Location:") to form.php, all the POST values are lost. You have to either resend them with the header, or modify them into GET and retrieve them again. It should be more efficient to have them both (contact.php AND form.php) in one page. That way, the form data only has to be sent once.
You could probably just send the POST values as GET over to form.php like this.
contact.php:
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject."&message=".$message);
form.php (to retrieve the values):
$name = $_GET['name'];
$email = $_GET['email'];
$message = $_GET['message'];
$subject = $_GET['subject'];
If you want to display form elements then you have to use this approach.
<form method="POST" action="contact.php">
Email<input type="text" name="email">
.......
.......
.......
// All elements
</form>
This may help you.
Give action in your form in contact.php
<form action="form.php">

How to validate email address [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to validate an email address in PHP
I was wondering someone can help me please.
I need to validate the email address for the below code but am having problems.
<?php
if ($_POST) {
$expected = array('name', 'email', 'emailmessage');
$validation = array(
'name' => 'Please provide your full name',
'email' => 'Please provide your valid email address',
'emailmessage' => 'Please provide message'
);
$errors = array();
$output = array();
foreach($expected as $key) {
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
if (empty($_POST[$key])) {
$errors[$key] = $validation[$key];
} else {
$output[$key] = $_POST[$key];
}
} else {
$errors[$key] = $validation[$key];
}
}
if (!empty($errors)) {
$array = array('error' => true, 'fields' => $errors);
} else {
// PROCESS FORM
// ---------------------------------------------------------
// BEGIN EDITING
// ---------------------------------------------------------
$to = "qakbar#hotmail.co.uk"; //This is the email address messages will be sent to
$web_name = "My Test Web Form"; //This is the name of your website that will show in your email inbox
//get IP address
$ip = $_SERVER['REMOTE_ADDR'];
//make time
$time = time();
$date = date("r", $time);
// ---------------------------------------------------------
// END EDITING
// ---------------------------------------------------------
$emailmessage = trim($emailmessage);
$emailmessage = nl2br($emailmessage);
$emailmessage = htmlspecialchars($emailmessage);
$emailmessage = wordwrap($emailmessage, 70);
//Visible form elements
$name = $_POST['name']; //Sender's name
$email = $_POST['email']; //Sender's email
$emailmessage = htmlspecialchars($_POST['emailmessage']); //Sender's message
//Setting up email
$subject = "New Message from $web_name";
$message = "
New message from $name <br/><br/>
Message:<br />
$emailmessage
<br/>
<br/>
Email: $email<br />
IP:</strong> <span style=\"color:#990000;\">$ip</span><br />
Date:</strong> $date
";
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$header .= 'From:'. $email . " \r\n";
$sent = mail($to, $subject, $message, $header);
//$message = '<div id=message>You have successfully subscribed to our newsletter</div>';
$array = array('error' => false, 'message' => $message);
}
echo json_encode($array);
}
I want the email to validate in the $validation array as my messages are passed through this and need the email validation to do the same.
I was trying to use the following but did not know where to place it or how to call it.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// email is valid
} else {
// email is invalid
}
Any help is much apprecaited.
Thank you
You could use it like this:
filter_var($email, FILTER_VALIDATE_EMAIL) or die("Email wrong.");
Right after you assigned this exact variable:
$email = $_POST['email'];
Of course this could be structured more sensible, and a nicer error notice would also be possible. But it sounds as if you need more general practice with PHP first.
An oddity with your code:
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
You're using the key already BEFORE checking if it exists. As well, the $input variable is not used again in your code, so it's a useless line.
May be, this code will help you. try it.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['uname'];
$email = $_POST['email'];
$valid_arr = array();
$error_arr = array();
if($name == ''){
$error_arr['name'] = 'Required';
}
else if(!preg_match('/^[a-zA-A]+$/',$name)){
$error_arr['name'] = 'Please put correct value';
}
else{
$valid_arr['name'] = $name;
}
if($email == ''){
$error_arr['email'] = 'Required';
}
else if(!preg_match('/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
$error_arr['email'] = 'Exm.- john#gmail.com';
}
else{
$valid_arr['email'] = $email;
}
if(count($error_arr) == 0){
header('location: success.php');
}
else{
echo 'Error in Loading';
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<table>
<tr>
<td><label>User Name :</label></td>
<td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
<td class="error"><?php echo $error_arr['name'];?></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
<td class="error"><?php echo $error_arr['email'];?></td>
</tr>
<tr>
<td><input type="submit" name="save" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>

Categories