Select case with array - php

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.

Related

Validation for registration page in PHP

I have a registration page and I want to validate it. I have this code:
$msg = "";
$msg_3 = "";
if(isset($_POST['submit'])) {
$First_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
$Last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$confirm_email = ((isset($_POST['confirm_email']))?sanitize($_POST['confirm_email']):'');
$mobile_number = ((isset($_POST['mobile_number']))?sanitize($_POST['mobile_number']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm_password = ((isset($_POST['confirm_password']))?sanitize($_POST['confirm_password']):'');
$gender = ((isset($_POST['gender']))?sanitize($_POST['gender']):'');
$day = ((isset($_POST['day']))?sanitize($_POST['day']):'');
$month = ((isset($_POST['month']))?sanitize($_POST['month']):'');
$year = ((isset($_POST['year']))?sanitize($_POST['year']):'');
$insurance = ((isset($_POST['insurance']))?sanitize($_POST['insurance']):'');
$agree = ((isset($_POST['agree']))?sanitize($_POST['agree']):'');
$sql = "SELECT email, mobile_number FROM customers WHERE email ='$email' OR mobile_number ='$mobile_number'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($email == $row['email']) {
$msg = "<span class='text-danger'>The email address you've entered is already associated with another account.
<br>Please sign in or enter a different email address. Please try again.</span>";
} if ($mobile_number == $row['mobile_number']) {
$msg_3 = "<span class='text-danger'>The mobile phone number you've entered is already associated with another account.
<br>Please sign in or enter a different number. Please try <br>again.</span>";
}
}
} else {
// Insert into database and send email
}
Now how could I validate each field if it is empty and print different messages under each field in this nested if and while. I'm getting confused.
If you will use same names in db as in form you could use something like this:
$keys = ['gender', 'email', 'mobile_number']; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($key) {
if (empty($row[$key])) {
$errors[] = "$key is required"
}
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[] = "please enter $key"
}
})
}
if you need to have more customized messages you might map keys to error text like:
$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($errorMsg, $key) {
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[$key] = $errorMsg['equal'];
}
if (empty($row[$key])) {
$errors[$key] = $errorMsq['empty'];
}
})
}
Do not repeat
Prevent SQL Injection
You can do something like this.
<?php
if(isset($_POST['submit'])) {
$errors = [];
function getPost($postIndex, $errorMessage = '') {
global $errors;
if (!empty( $_POST[$postIndex] )) {
$value = $_POST[$postIndex];
return $value;;
} else {
$errors[$postIndex] = $errorMessage;
return null;
}
}
function validateString($s) {
return htmlspecialchars(trim($s));
}
getPost('First_Name', 'Firstname Cannot Be Empty');
getPost('Last_Name', 'Lastname cannot be empty');
$email = getPost('email', 'Your Error Message');
getPost('confirm_email', 'Your Error Message');
$mobile_number = getPost('mobile_number', 'Your Error Message');
getPost('password', 'Your Error Message');
getPost('confirm_password', 'Your Error Message');
getPost('gender', 'Your Error Message');
getPost('day', 'Your Error Message');
getPost('month', 'Your Error Message');
getPost('year', 'Your Error Message');
getPost('insurance', 'Your Error Message');
getPost('agree', 'Your Error Message');
$stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');
if (
$stmt &&
$stmt -> bind_param('ss', $email, $mobile_number) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($dbEmail, $dbMobileNumber) &&
$stmt -> fetch()
) {
if ($email == $dbEmail) {
// email equal error message
} if ($mobile_number == $row['mobile_number']) {
// mobile number equal error message
}
}
if (count($errors)) {
echo "You have an error";
}
// or get the post index in your HTML form and show the error message there
// <?php isset($errors['firstName']) ? echo $errors['firstname'] : null;
}

how to get value from text file in php

I have script that make comparison between value from page php and data store in txt file, and then it will do some special code.
Content of txt file (account.txt)
F: user pass { expire=date; afexpire=date; email=email#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
F: mike fghg58g { expire=2016-05-24; afexpire=2015-5-24 17; email=mike#gmail.com; Country=uk; visit_from=none; ip=none; hosted=none }
F: adresson f5849dh9d { expire=2016-11-01; afexpire=2015-11-01 17; email=mike#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
my script
<?php
$user = "Mike"; // user that is inserted in page form
$email = "mike#gmail.com"; // email that is inserted in page form
$userFile = "Mike"; // user in txt file
$emailFile = "mike#gmail.com"; // email in txt file
if( $user == $userFile && $email == $emailFile ) {
echo "The user and email is used";
} elseif( $user == $userFile && $email != $emailFile ) {
echo "The user is used";
} else{
// do special code
}
I don't know how to read file txt from path and change user and email in file to value to make comprison
$userFile = "Mike"; // user in txt file (account.txt)
$emailFile = "mike#gmail.com"; // email in txt file (account.txt)
This is my spcial script that make output in (account.txt)
<?php
if (isset($_POST["g-recaptcha-response"])) {
$name = $_POST['name'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$country = $_POST['country'];
$plan = $_POST['plan'];
$quantity = $_POST['quantity'];
$payment = $_POST['payment'];
$reciever = $_POST['reciever'];
$captcha = $_POST['g-recaptcha-response'];
$message_user = $_POST['message'];
$serverip = $_POST['REMOTE_ADDR'];
$to = 'sup.alphas#gmail.com';
$parts = explode("#", $email);
$sufemail = $parts[0];
// $sufemail = substr(strstr($email, '#'), 1); for domain//
$subject_form = 'Request new account by '.$sufemail.'';
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if name has been entered
if (!$_POST['user']) {
$errUser = 'Please enter your username';
}
// Check if name has been entered
if (!$_POST['pass']) {
$errPass = 'Please enter your password';
}
// Check if email has been entered and is valid
if (!$_POST['email']) {
$errEmail = 'Please enter a valid email address';
}
if (!$_POST['country']) {
$errCountry = 'Please enter your country';
}
if (!$_POST['plan']) {
$errPlan = 'Please enter your plan';
}
if (!$_POST['quantity']) {
$errQuantity = 'Please enter your quantity';
}
if (!$_POST['payment']) {
$errPayment = 'Please enter your method of payment';
}
if (!$_POST['g-recaptcha-response']) {
$errCaptcha = 'Please enter captcha';
}
// If there are no errors, send the email
if (!$errName && !$errUser && !$errPass && !$errEmail && !$errCountry && !$errPlan && !$errQuantity && !$errPayment && !$errCaptcha) {
// Start Create new account //
$dateadd = date('Y-m-d', strtotime("$plan"));
$datetry = date('Y-m-d H', strtotime("+1 day"));
$handle = fopen('/usr/www/users/alphacz/alpha/phpm/account.cfg', 'a');
fwrite($handle, 'F: ' . $_POST["user"] . ' ' . $_POST["pass"] . ' { expire=' . $datetry . '; afexpire=' . $dateadd . '; email=' . $email . '; Country=' . $country . '; visit_from=none; ip=none; hosted=' . $_POST['REMOTE_ADDR'] . " }\r\n");
fclose($handle);
Help me, please
Thank you
You can check a needle in a haystack which is your account file here.
username pattern is "F: {user} pass {..."
email pattern is "; email={email}; Country="
Note: You must also think that this excample check keywords incasesensitive, so
when searching and inserting, you should convert keywords to lowercase
$user_used = userExists('Mike');
$email_used = emailExists('mike#gmail.com');
if ($user_used && $email_used)
{
echo 'The user and email is used';
}
elseif ($user_used) {
echo 'The user is used';
}
else
{
//do special code
}
function userExists($user)
{
return (exec('grep ' . escapeshellarg('F: ' . $user . ' ') . ' {file-path}'));
}
function emailExists($email)
{
return (exec('grep ' . escapeshellarg('; email=' . $email . ';') . ' {file-path}'));
}
We could fix your current code to read from the file, but instead we first rewrite your code which writes to the file, so it will be way easier to read from the file afterwards.
(Since you only show part of the script which writes to the file I can only rewrite that part.)
Changes
JSON format for the file
Instead of writing your data into the file in a custom format we will save the data in JSON format. You can easily work with JSON in PHP since it has built-in functions to work with it.
$_POST ↔ $_SERVER ?
At some point you use $_POST['REMOTE_ADDR'], but I assume that you wanted to use $_SERVER["REMOTE_ADDR"]. See: http://php.net/manual/en/reserved.variables.server.php.
!$XY
While using !$XY as condition may work sometimes it isn't very practical. Since it simply negates the value and then checks if it is a truthy or falsey value and should enter the if statement or not. So I would recommend you to use !empty() to check if your input is set and is not empty.
Code
<?php
if (isset($_POST["g-recaptcha-response"])){
$checkPostIndices = ["name", "user", "pass", "email", "phone", "country", "plan", "quantity", "payment", "reciever", "g-recaptcha-response", "message"];
$data = [];
$errors = [];
$errorMessages = [
"name" => "Please enter your name",
"user" => "Please enter your username",
"pass" => "Please enter your password",
"email" => "Please enter a valid email address",
"phone" => "Please enter your phone number",
"country" => "Please enter your country",
"plan" => "Please enter your plan",
"quantity" => "Please enter your quantity",
"payment" => "Please enter your method of payment",
"reciever" => "Please eneter a reciever",
"g-recaptcha-response" => "Please enter captcha",
"message" => "Please enter a message",
];
foreach($checkPostIndices as $index){
if(!empty($_POST[$index])){
$data[$index] = $_POST[$index];
} else {
$errors[] = $errorMessages[$index];
}
}
$data["serverip"] = $_SERVER["REMOTE_ADDR"];
$to = "sup.alphas#gmail.com";
$sufemail = explode("#", $data["email"])[0];
$subject_form = "Request new account by " . $sufemail;
if(!empty($errors)){
$fileData = array_intersect_key($data, ["user", "pass", "email", "country", "serverip"]);
$fileData["dateadd"] = date("Y-m-d", strtotime($data["plan"]));
$fileData["datetry"] = date("Y-m-d H", strtotime("+1 day"));
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$file = empty($file) ? [] : json_decode($file, TRUE);
$file[] = $fileData;
file_put_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg", json_encode($file));
}
}
?>
So now after that your data should be stored in JSON like this:
[
{"key":"data"}
//...
]
And then you can easily use json_decode() to decode your file into an array, loop through the array and check if the email and user are already used.
Code
<?php
$user = "Mike";
$email = "mike#gmail.com";
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$data = json_decode($file, TRUE);
foreach($data as $v){
if($v["user"] == $user && $v["email"] == $email){
echo "Email and user already used";
}
}
?>

Can't figure out how to format this logic statement in PHP

I have some PHP I'm using to validate a form, and once the validation is complete the data from the form is sent into a database. My problem isn't actually a code problem, it's just I can't figure out how to write the if-else statement blocks.
Basically I have all these if statements that check if one of the form fields is empty or doesn't meed the criteria, and then a corresponding else statement which simply holds the data they've entered, so when the form reloads they don't have to enter it in again. At the moment I have an else statement at the end which posts all the data into my database when all the fields are validated - the problem is that I have one too many else statements and it gives me errors for this.
So I figure I have to wrap the whole block of code in one if-else statement, that would basically say if there are no errrors, do the else which sends the data to the database.
Basically I have the else done, I just need help to think of what condition to put for the if
Here's my code
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
## Initialise varialbes to null ##
$nameError ="";
$emailError ="";
$categoryError ="";
$messageError ="";
$validName ="";
$validEmail ="";
$validMessage ="";
## On submitting form below function will execute ##
if(isset($_POST['submit']))
{
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$category = $_POST['category'];
//if name is less than 10 characters
if (empty($_POST["name"]) || strlen($name)<10)
{
$nameError ="* Name is too short";
}
else
{
$validName = $_POST["name"];
}
//if email is too short or is not the right format
if (empty($_POST["email"]) || !preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email) || strlen($email)<10 )
{
$emailError = "* You did not enter a valid email";
$validEmail = $_POST["email"];
}
else
{
$validEmail = $_POST["email"];
}
//if a category is not chosen
if (empty($_POST["category"])) {
$categoryError = "* Please select a category";
}
//if the message is left blank
if (empty($_POST["message"]) || strlen($message)<25 ) {
$messageError = "* Your message is too short";
}
else {
$validMessage = $_POST["message"];
}
//If there are no errors, email details to admin
else {
// variables to send email
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $_POST[category] \r\n
Message: $_POST[message] \r\n
Name: $_POST[name] \r\n
Email: $_POST[email]";
// Email Function
mail($to,$subject,$body);
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
}
?> <!-- End of PHP -->
Essentially I need to figure out another if statement to put just after the first one, but for the life of me I can't think of a condition to have. I thought what if I made a boolean that was false, and once all the data is correct it is put to true, but I can't figure out how to implement it. Just looking for any ideas on how to go about it
When I do validation, I personally try to come up with a function that will validate each value similarly. There are a few checks you should be doing as you go. Here is a restructure of what you have with some notations:
<?php
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
// I usually build a simple validate function
// This is just an example, you can edit based on your needs
function validate_var($value = false,$type = 'str')
{
// Validate the different options
if(!empty($value) && $value != false) {
switch ($type) {
case ('str'):
return (is_string($value))? true:false;
case ('num') :
return (is_numeric($value))? true:false;
case ('email'):
return (filter_var($value,FILTER_VALIDATE_EMAIL))? true:false;
}
// This will just check not empty and string length if numeric
if((is_numeric($type) && !empty($value)) && (strlen($value) >= $type))
return true;
}
// Return false if all else fails
return false;
}
// On post, proceed
if(isset($_POST['submit'])) {
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
// Strip the message of html as a precaution
// Since you are not binding in your sql lower down, you should probably use
// htmlspecialchars($_POST['message'],ENT_QUOTES))
// or use the binding from the mysqli_ library to escape the input
$message = htmlspecialchars(strip_tags($_POST['message']),ENT_QUOTES));
// Do a "just-incase" filter (based on what this is supposed to be)
$category = preg_replace('/[^a-zA-Z0-9]/',"",$_POST['category']);
// Validate string length of 10
if(!validate_var($name,10))
$error['name'] = true;
// Validate email
if(!validate_var($email,'email'))
$error['email'] = true;
// Validate message length
if(!validate_var($message,25))
$error['message'] = true;
// Validate your category
if(!validate_var($category))
$error['category'] = true;
// Check if there are errors set
if(!isset($error)) {
// Use the filtered variables,
// not the raw $_POST variables
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $category \r\n
Message: $message \r\n
Name: $name \r\n
Email: $email";
// Don't just send and insert, make sure you insert into your databases
// on successful send
if(mail($to,$subject,$body)) {
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
else
echo 'An error occurred.';
}
else {
// Loop through errors cast
foreach($error as $kind => $true) {
switch ($kind) {
case ('name') :
echo "* Name is too short";
break;
case ('email') :
echo "* You did not enter a valid email";
break;
case ('category') :
echo "* Please select a category";
break;
case ('message') :
echo "* Your message is too short";
break;
}
}
}
}
?>

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

PHP Feedback form Checkbox error

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.

Categories