PHP OOP - How to validate input fields correctly - php

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.

Related

PHP validation showing wrong icon

I am new to PHP. I am here trying to show error icon when validation fails
PHP
<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
}
?>
HTML
<div class="<?php if (empty($nameErr)){ echo 'success-validate';} else { echo 'failure-validate'; } ?>">
</div>
Here, I am always getting the success-validate icon when the page loads for first time. But when I click the submit button, the validation is working fine. Please help me resolve the issue.
So, the problem here is that you have 3 states (valid, no-valid and no-validation-used) instead of two as you think of at first.
So, the simplest solution can be to add another flag which tells that validation has started, eg:
// define variables and set to empty values
$nameErr = "";
$name = "";
$validationApplied = false; // here
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$validationApplied = true;
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
}
In your html you then can check both variables like this:
<div class="<?php if ($validationApplied) { echo empty($nameErr) ? 'success-validate' : 'failure-validate'; } ?>">
</div>
Another solution can be to check both $nameErr and $_SERVER["REQUEST_METHOD"] == "POST". It's the same as above approach, just instead of distinct flag you check REQUEST_METHOD:
<div class="<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { echo empty($nameErr) ? 'success-validate' : 'failure-validate'; } ?>">
</div>

Passing variables into a mysqli prepared statement

I have been self teaching myself php in my spare time using you tube and w3 schools. So far I have been mostly successful but have hit a brick wall with a particular issue.
I am trying to use a prepared statement to load data into a database (Xampp myphp admin). I have attached my code below and have done a range of testing based on internet searches. When I run the code I get no error message but nothing inserts into my database. I am fairly certain it is do with passing the variables into the bind_param() placeholders.
Please ignore the fact the headings don't match the data types as I want to get data inserting into the database first.
Thanks
<?php
include 'dbh.php';
class AddData extends Dbh {
public function submitTableData(){
$dateErr = $starttimeErr = $finishtimeErr = $durationErr = $taskErr = $entityErr = $completeErr = $commentsErr = "";
$date = $starttime = $finishtime = $duration = $task = $entity = $complete = $comments = "";
$query = "INSERT INTO testtable(Date, Starttime, Finishtime, Duration, Task, Entity, Complete, Comments) VALUES (?,?,?,?,?,?,?,?)";
$stmt= $this->connect()->prepare($query);
$stmt->bind_param("ssssssss", $date, $starttime, $finishtime, $duration, $task, $entity, $complete, $comments);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
for ($x = 0; $x < 1; $x++) {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"][$x])) {
$dateErr = "date is required";
} else {
$date = test_input($_POST["date"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$date)) {
$dateErr = "Only letters and white space allowed";
}
}
if (empty($_POST["starttime"][$x])) {
$starttimeErr = "starttime is required";
} else {
$starttime = test_input($_POST["starttime"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$starttime )) {
$starttimeErr = "Only letters and white space allowed";
}
}
if (empty($_POST["finishtime"][$x])) {
$finsihtimeErr = "finishtime is required";
} else {
$finishtime = test_input($_POST["finishtime"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$finishtime)) {
$finishtimeErr = "Only letters and white space allowed";
}
}
if (empty($_POST["duration"][$x])) {
$durationErr = "Name is required";
} else {
$duration = test_input($_POST["duration"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$duration)) {
$durationErr = "Only letters and white space allowed";
}
}
if (empty($_POST["task"][$x])) {
$taskErr = "task is required";
} else {
$task = test_input($_POST["task"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$task)) {
$taskErr = "Only letters and white space allowed";
}
}
if (empty($_POST["entity"][$x])) {
$entityErr = "Name is required";
} else {
$entity = test_input($_POST["entity"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$entity)) {
$entityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["complete"][$x])) {
$completeErr = "complete is required";
} else {
$complete = test_input($_POST["complete"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$complete)) {
$completeErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comments"][$x])) {
$commentsErr = "comments is required";
} else {
$comments = test_input($_POST["comments"][$x]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comments)) {
$commentsErr = "Only letters and white space allowed";
}
}
}
$stmt->execute();
}
$stmt->close();
$this->connect()->close();
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$t1 = new AddData;
$t1->submitTableData();
}
?>

PHP - Validation form

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" ) {

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

Categories