PHP - Validation form - php

I'm trying to create a simple validation script for a form but cannot get it to work properly. I only get redirected to an error page...
As you can see below only small and capitalized letters are allowed for first- and last name, only email structure for email and only numbers, spaces and (+) for the phone number. If the user input is not allowed the user gets redirected to a simple error page.
$first_name = $last_name = $email = $mobile = $country = "";
if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {
// Only small and capitalized letters allowed
$first_name = test_input($_POST['first_name']);
if(!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
die("Error! Non allowed signs were used in 'first name'");
}
// Only small and capitalized letters allowed
$last_name = test_input($_POST['last_name']);
if(!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
die("Error! Non allowed signs were used in 'last name'");
}
// Only email allowed
$email = test_input($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die ("Error! Non allowed signs were used in 'email'");
}
// Only numbers, space and + allowed
$mobile = test_input($_POST['mobile']);
if(!preg_match("/^[0-9 +-]+$/",$mobile)) {
die ("Error! Non allowed signs were used in 'mobile'");
}
// Country input (no validation)
$country = $_POST['country'];
}
// Function test input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The HTML is basically this:
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" required="" name="first_name" style="width:100%" />
[And so on...]
</form>

if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {`
is incorrect ~ isset returns a boolean which effectively makes this if(false=='POST') or similar
Try:
if ( $_SERVER["REQUEST_METHOD"] == "POST" ) {

Related

PHP OOP - How to validate input fields correctly

This is my Form - This an Include File.
form_file.php
<section class="container-sm">
<form method="post" class="par-form">
<h3 class="par-h2">John Doe Form</h3>
<p><label class="single-label" for='user_firstname'>Name: <a id='user_firstname_label'></a></label>
<input class="par-input form_login" maxlength="15" name="user_firstname" required value="<?=$obVaga->user_firstname?>" ></input><span class="error">*<?php echo $nameErr;?></span></p>
<p><label class="single-label" for='user_secondname'>Surname: <a id='user_secondname_label'></a></label>
<input class="par-input form_login" maxlength="40" name="user_secondname" required value="<?=$obVaga->user_secondname?>" ></input></p>
<p><label class="single-label" for='user_email'>E-mail: <a id='user_email_label'></a></label>
<input class="par-input form_login" maxlength="40" name="user_email" required value="<?=$obVaga->user_email?>" ></input></p>
<button type="button" onclick="sendData()" class="par-button" id='user_button_sendData'>SEND</button>
</form>
</section>
This is the template page that receives the Form file
single-add.php
<?php
/**
* Acess the composer library
*/
require __DIR__.'/vendor/autoload.php';
/**
* Use a Classe VAGA
*/
use \App\Entity\Vaga;
$obVaga = new Vaga;
if (isset($_POST['user_firstname'],$_POST['user_secondname'],$_POST['user_email'])) {
$obVaga->user_firstname = $_POST['user_firstname'];
$obVaga->user_secondname = $_POST['user_secondname'];
$obVaga->user_email = $_POST['user_email'];
$obVaga->user_cadastrar();
}
?>
<!-- Receive the contents of the form include form_file.php -->
<?php include __DIR__.'/appincludes/form_file.php' ?>
This is the Class page that receives the data
Vaga.php
<?php
namespace App\Entity;
/**
* Use a Classe Database
*/
use \App\Db\Database;
use PDO;
class Vaga{
// #var Integer
public $user_id;
// #var String
public $user_firstname;
// #var String
public $user_secondname;
// #var String
public $user_email;
// #var String
public $nameErr;
// #var Boolean
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_firstname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_secondname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_secondname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
public function user_cadastrar(){
// DEFINIR A DATA
// INSERT STRINGs IN THE TABLE
$obDatabase = new Database('tb_partner');
$this->id = $obDatabase->insert([
'user_firstname' => $this->user_firstname,
'user_secondname'=> $this->user_secondname,
'user_email' => $this->user_email
]);
}
}
I´m trying to use this script to validate the fields, but I am stuck. I`m trying to execute this script through the class file Vaga.php
public function par_add_validate(){
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_firstname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_secondname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_secondname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
};
}
I putted the Var $nameErr in the form_file.php where it should display an echo string IF the field is empty or with not acceptable letters.
This is the result in the debug.log file:
[18-Aug-2021 16:44:07 UTC] PHP Notice: Undefined variable: nameErr in C:\xampppserver2\htdocs\project\appincludes\form_file.php on line 15
Line 15:
<input name="user_firstname" required value="<?=$obVaga->user_firstname?>" ></input><span>*<?php echo $nameErr;?></span></p>
What am I doing wrong or what is missing?
I believe you have some lines missing here:
// #var Boolean
if ($_SERVER["REQUEST_METHOD"] == "POST") {
Otherwise you've put some logic code right inside your class (without method) which should result in a Parse error. Also why is there #var Boolean with no boolean property following?
Given that you wrap all that code in a method, you still have several issues. First, you can't access $nameErr directly. Instead, you want $this->nameErr.
And in form_file.php you also have no variable called $nameErr. You have nameErr as a property of $obVaga object though. You can access it using $obVaga->nameErr.

User registration form error php

Hi am trying to write code that validates in the backend. The code should stop as soon as there is an error. In my case, even if the conditions are satisfied the code stops in the first name validation block itself.
Also I wish to have only backend validation.
Here is the php code clientRegister.php
<?php
require_once("connection.php");
session_start();
// define variables and set to empty values
$clientFirstName = $clientLastName =$clientEmail = $clientPassword =
$clientCPassword = $clientContact = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// First Name Validation
if (empty($_POST["clientFirstName"])) {
die("error: empty field");
} else {
$clientFirstName = test_input($_POST["clientFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
}
// Last Name Validation
if (empty($_POST["clientLastName"])) {
die("error: empty field");
} else {
$clientLastName = test_input($_POST["clientLastName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientLastName)) {
die("Error: Only letters and white space allowed");
}
}
// Email Validation
if (empty($_POST["clientEmail"])) {
die("error: empty field");
} else {
$clientEmail = test_input($_POST["clientEmail"]);
// check if e-mail address is well-formed
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
die("Error: Invalid email format");
}
}
// Password Validation
if (empty($_POST["clientPassword"])) {
die("error: empty field");
}
// Confirm Password Validation
if (empty($_POST["clientCPassword"])) {
die("error: empty field");
}
if ($clientPassword != $clientCPassword) {
die("error: passwords mismatch");
}else{
$hashedClientPassword = password_hash($clientPassword, PASSWORD_DEFAULT);
}
if (empty($_POST["clientContact"])) {
die("error: empty field");
} else {
$clientContact = test_input($_POST["clientContact"]);
// check if number is correct
if (!preg_match("[0-9]",$clientContact)) {
die("error: Only 0-9 allowed");
}
}
$check_email = $conn->query("SELECT clientEmail FROM tbl_clients WHERE
clientEmail='$clientEmail'");
$emailCount=$check_email->num_rows;
if ($emailCount==0) {
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName,
clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
if ($newClient === false){
$result = array();
$result[] = array("status" => "Error");
}else{
echo "Your have been signed up - please now Log In";
$result = array();
$result[] = array("First Name" => $clientFirstName, "Last Name" => $clientLastName, "Email" => $clientEmail, "Password" => $hashedClientPassword, "Contact" => $clientContact, "status" => "success");
}
}else {
echo "Already Exists";
$result = array();
$result[] = array("status" => "Error");
}
echo json_encode($result);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>Reg User</h2>
<form method="post" action="clientRegister.php">
<label>
First Name:<input type="text" name="clientFirstName"><br/>
Last Name:<input type="text" name="clientLastName"><br/>
Email:<input type="text" name="clientEmail"><br/>
Password:<input type="password" name="clientPassword"><br/>
Confirm Password:<input type="password" name="clientCPassword"><br/>
Contact:<input type="text" name="clientContact"><br/>
<input type="submit" value="Register" name="submit">
</label>
</form>
</body>
</html>
You have missing pattern delimiters for your preg_match()
Replace your patterns with following sample:
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
With:
if (!preg_match("/[a-zA-Z ]/",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
Also your
($clientPassword != $clientCPassword)
will always return false because you have not assigned new $_POST values to them. And since you have initialized both variables as empty. So (empty != empty) always return false.
So you should compare like this:
($_POST["clientPassword"] != $_POST["clientCPassword"])
Regarding your query, it was not executed
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
Which I think you meant:
$newClient = $conn->query("INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')");
Note: Your queries are vulnerable to sql injection and you should use prepare statement
DEMO:
http://sandbox.onlinephpfunctions.com/code/d435ae025dc9e22b677823ff37712bb712b71e1b
You can test this file:
https://pastebin.com/AgfquEMC

How to set validation on Phone number in PHP

This is my code:
I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation,
I enter text in the phone number field, they accept in backend
what can I do? for set validation for phone number field.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $phoneErr = "";
$name = $phone = "";
$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = htmlspecialchars($_REQUEST['name']);
$phone = htmlspecialchars($_REQUEST['phone']);
if (empty($name)) {
$nameErr = "* Name is required";
$error = 1;
// echo "Name is empty";
}
if (empty($phone)) {
// echo "phone is empty";
$phoneErr = "* Phone is required";
$error = 1;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<h1>Login Form</h1>
Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
<span class="error"> <?php echo $nameErr?></span>
<br></br>
Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
<span class="error"> <?php echo $phoneErr?></span>
<br><br>
<input type="submit">
<br><br>
</form>
</body>
</html>
I need to validate phone number in PHP, but the example do not work.
How can I set validation for mobile number
Sorry to answer an old post.
However, you can check if the number exists by calling a web service.
In this case, I found numverify.com, allowing to verify if a phone number exists.
After creating a free account (allows you to make 250 requests each month), you can invoke the following basic code in PHP:
// set API Access Key
$access_key = 'YOUR_ACCESS_KEY';
// set phone number
$phone_number = '14158586273';
// Initialize CURL:
$ch = curl_init('http://apilayer.net/api/validate?access_key='.$access_key.'&number='.$phone_number.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Store the data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$validationResult = json_decode($json, true);
I have no idea if this is reliable, but it worked with my phone number and even retrieved the company carrier.
According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.
$tel = '091-9869123456';
if(preg_match("/^[0-9]{3}-[0-9]{10}$/", $tel)) {
echo "valid";
} else {
echo "invalid";
}
Now for more validating need to check country code:
if(substr($tel, 0, 3) == '091'){
echo "valid";
} else {
echo "invalid, it should start with 091";
}
Or you do this with same preg_match like this:
if(preg_match("/^[091]{3}-[0-9]{10}$/", $tel)) {
echo "valid";
} else {
echo "invalid";
}
Demo
Why do you need to validate phone number using php?
You can do it using JS as shown below.
if (/^\+[-0-9]{6,20}$/.test(phoneNumber) == false) {
alert('Wrong Phone Number format. Only numbers,+ and - are allowed. Format: \<Country Code\>\<Phone number\> Eg: +9199999999, +1-105-893-9334 etc');
return;
}

PHP - Form validation functions. How to use functions to write better code?

I'm practicing doing simple form validation and have come unstuck trying to use a function to replace code that I repeat several times throughout the validation script.
I am trying to write a function that saves an error message to an $errors array when validation fails for that form field.
The function I'm using does not return any error messages but does not display the message that is should do when validation fails.
I'm testing it on just one filed, the username field and with just one validation rule, username cannot be blank.
NB/ The form and validation worked when I was not trying to use a function.
Here is what I have, what a I doing wrong? I'm struggling to get to grips with functions :-(
functions.php
<?php
//Function to deal with saving error messages to errors array
// #param - 2 parameters. Name of field that has the error; Error message string
// #return - an error message string
function errorHandler($errField, $errMsg){
$errors[$errField] = $errMsg;
return $errors;
}
index.php
<?php
include_once '_includes/headers.php';
include_once '_includes/functions.php';
?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Initialize variables
$data = array();//Store cleaned valid data for output
$errors = array();//Store error messages
$form_is_submitted = false;
$errors_detected = false;
if(isset($_POST['registerBtn'])){
$form_is_submitted = true;
//VALIDATE FORM
//Validate - Username
if (isset($_POST['username'])) {
$username = trim($_POST['username']);
//Username cannot be blank - validation
if($username !== ''){
$data['username'] = htmlentities($username);
//Get the length of the string
$stringLength = strlen($username);
//Username minimum 5 maximum 15 characters long - validation
if($stringLength < 5 || $stringLength > 15){
$errors_detected = true;
$errors['username'] = ' Invalid length. Must be between 5 - 15 characters!';
}else {
$data['username'] = htmlentities($username);
}
//Username must only be alphanumeric characters - validation
if(!ctype_alnum($username)){
$errors_detected = true;
$errors['username'] = ' Invalid characters. Alphanumeric characters only!';
}else {
$data['username'] = htmlentities($username);
}
}else {
$errors_detected = true;
//Call error message function
if($errors_detected === true){
errorHandler('username', ' Field cannot be blank!');
}
}
}else {
$errors_detected = true;
$errors['username'] = ' Is not set!';
}
//Validate - Email
if(isset($_POST['email'])){
$email = trim($_POST['email']);
//Email cannot be blank - validation
if($email !== ''){
$data['email'] = htmlentities($email);
//Email must be valid format - validation
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors_detected = true;
$errors['email'] = ' Invalid email format!';
}else {
$data['email'] = htmlentities($email);
}
}else{
$errors_detected = true;
$errors['email'] = ' Email address is required!';
}
}else {
$errors_detected = true;
$errors['email'] = " is not set!";
}
}
//Declare form output variable
$output = '';
//IF VALID SUBMISSION
if($form_is_submitted === true && $errors_detected === false){
$output .= '<h3>Form successfully submitted</h3>';
echo $output;
foreach($data as $keys => $values){
echo "<p>$keys : $values</p>";
}
} else {
//IF INVALID SUBMISSION
if($errors_detected === true){
$output .= '<h2>There are errors on the form</h2>';
echo $output;
foreach($errors as $key => $value){
echo "<p>" . htmlentities($key) . ':' . htmlentities($value) . "</p>";
}
}
//DISPLAY/REDISPLAY FORM
$self = htmlentities($_SERVER['PHP_SELF']);
$output ='
<form action="'. $self .'" method="post">
<fieldset id="registration">
<legend>Register</legend>
<p>Insert your profile information:</p>
<div>
<label for="username">Username</label>
<input id="username" name="username" type=text value="' . (isset($data['username']) ? $data['username'] : '') . '" />
</div>
<div>
<label for="email">Email</label>
<input id="email" name="email" type=email value="' . (isset($data['email']) ? $data['email'] : '') . '" />
</div>
<input type="submit" id="registerBtn" name="registerBtn" value="Register" />
</fieldset>
</form>
';
echo $output;
}
?>
<?php
include_once '_includes/footers.php';
?>
UPDATE:
I have updated my function to use the $errors array in my function. This should now no longer be a scope issue I think. As per Francesco Malatesta below ...
First of all, you should study something about objects, classes, exceptions and more complex stuff for this kind of job. I am assuming you want to learn about functions and do some practice.
You should, first of all, pass the errors array as a parameter.
Like this:
function errorHandler($errorsArray, $errField, $errMsg){
$errorsArray[$errField] = $errMsg;
return $errorsArray;
}
And then, in your index.php file:
errorHandler($errors, 'username', ' Field cannot be blank!');
This should work, because you must use the $errors array in your function. It's a scope-related problem.
However, after this, forget everything (well, not everything) and study OOP and Exceptions :)
Have you heard about Exceptions?
Simple example to use a exception:
<?php
try {
// your if's
if(40 > 30) {
throw new Exception("40 is a bigger");
}
} catch (Exception $error) {
echo 'Your error is: '.$error->getMessage();
}
?>

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