php validate post request before add to data base - php

i have an a project im using php and flutter for that
when i want to add a data to database i want to validate user inputs in php
im using a postman to test it i want to all inputs correct that add on database can some one help me?
when i request a post add and user want to add data to database i want all inputs correct as i defined on below if one inputs not correct i want to tell that filed incorrect and do not add a data utill all inputs correct
if ($_SERVER["REQUEST_METHOD"] === 'POST') {
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (empty($_POST['First_Name'])) {
echo 'Error! You didnt Enter the First Name. <br />';
} else {
$first_name = $_POST['First_Name'];
if (!preg_match("/^[a-zA-z]*$/", $first_name)) {
echo 'Only alphabets and whitespace are allowed For First Name. <br />';
}
}
if (empty($_POST['Last_Name'])) {
echo 'Error! You didnt Enter the Last Name. <br />';
} else {
$last_name = $_POST['Last_Name'];
if (!preg_match("/^[a-zA-z]*$/", $last_name)) {
echo 'Only alphabets and whitespace are allowed For Last Name. <br />';
}
}
if (empty($_POST['Email'])) {
echo 'Email Address Is Required <br />';
} else {
$email = $_POST['Email'];
if (!preg_match($pattern, $email)) {
echo 'Email is not valid! <br />';
}
}
if (empty($_POST['Phone'])) {
echo 'Phone Number is Required! <br />';
} else {
$phone = $_POST['Phone'];
if (!preg_match('/^[0-9]*$/', $phone)) {
echo 'Only Numeric Value Is Allowed. <br />';
} elseif (!preg_match('/^0\d{10}$/', $phone)) {
echo 'Invalid Phone Number!';
} elseif (preg_match('/^0\d{10}$/', $phone)) {
$re = "SELECT * FROM user WHERE Phone=$phone ";
$reresult = mysqli_query($conn, $re);
if (mysqli_num_rows($reresult) > 0) {
echo "user has already registered! <br />";
}
}
}
$first_name = mysqli_real_escape_string($conn, $_POST['First_Name']);
$last_name = mysqli_real_escape_string($conn, $_POST['Last_Name']);
$email = mysqli_real_escape_string($conn, $_POST['Email']);
$phone = mysqli_real_escape_string($conn, $_POST['Phone']);
$dob = mysqli_real_escape_string($conn, $_POST['DOB']);
$sql = "INSERT INTO `user` (`First_Name`,`Last_Name`,`Email`,`Phone`,`DOB` )
VALUES('$first_name','$last_name','$email','$phone','$dob')";
$query = mysqli_query($conn, $sql);
//$check=mysqli_fetch_array($query);
if ($query) {
echo ' user successfully added!';
} else {
echo 'failure';
}
//phone else
}
im asking to solve my problem

Related

PHP phone number validation

I am trying to display error messages to user if they entered a wrong uk phone number format or not a number, but the error messages not working.
HTML
<input type="text" name="phone" class="form-control" value="<?php echo $phone;?>" placeholder="Mobile Number ">
<span class="error"><?php echo $phoneErr;?></span>
PHP
$phoneErr = "";
$phone = "";
if (empty($_POST["phone"])) {
$phone = "";
} else if(!preg_match( $phone, '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4}) $/'))
{
$phoneErr = "Invalid phone number";
}else {
$phone = test_input($_POST["phone"]);
}
test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
If it's not a number nothing will be inserted to the database, but if I typed a number 9223372036854775807 will be inserted, this value is not the one I entered. I have done some researches, I think this value means invalid string.
Other parts of my form are working fine only the phone number not working well, I am not sure why.
First of all: your regular expression (even purged by final space) doesn't match 9223372036854775807.
You don't show how you insert values in database, but if above code is for checking the phone number, it's a mystery how any phone number can be inserted, unless you insert $_POST['phone']. But why you insert $_POST['phone'] if you before try to convert it in $phone?
I say “try”, because in fact the line $phone = test_input($_POST["phone"]) never happens.
If $_POST['phone'] is empty, you set $phone to empty string (this in unnecessary: $phone is already an empty string, but this is not a problem), otherwise you test your regular expression, but you test it on $phone (an empty string), not on $_POST['phone']; in addition, you invert preg_match arguments, so in fact you test if an empty pattern matches string /^(?:\(\+?44\)\s?|\ ....
You have to rewrite your check routine in something like this:
$phoneErr = False;
$phone = "";
if( ! empty( $_POST["phone"] ) )
{
$pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
if( !preg_match( $pattern, $phone ) )
{
$phoneErr = "Invalid phone number";
}
else
{
$phone = test_input($_POST["phone"]);
}
}
(...)
if( $phoneErr )
{
// Your error routine here
}
elseif( $phone )
{
// Insert $phone (not $_POST['phone']) to database
}
Regarding your regular expression, check it with more than one UK valid numbers on regex101.com before using it. As alternative, you can try the regular expressions suggested in question cited in comments.
Solved
<?php
require_once('connect.php');
if(isset($_POST['submit']))
{
$name= strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
if($name=="") {
$error[] = "Please enter name.";
}
else if(!preg_match('/^[a-zA-Z ]*$/', $name))
{
// check if name only contains letters and whitespace
$error[] = "Only letters and white space allowed for name";
}
else
{
if( !empty($phone) )
{
$pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
if(!preg_match($pattern, $phone)){
$error[] = 'Please enter a valid phone number!';
}else{
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt =$conn->prepare( "INSERT INTO contact (name,phone)
VALUES( :name, :phone)");
$stmt->bindparam(':name', $name);
$stmt->bindparam(':phone', $phone);
$stmt->execute();
}catch(PDOException $e) {
echo "Error: " . $e->getMessage();
die();
}
}
}
}
}
?>

Values get inserted in database without entering data

I m trying a contact form in php where the details as to get stored in the database.If i dont enter any values it displays error msg but it gets stored in the database. How can I validate form when error message displays the data should not be entered in database.
Here is the code
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$name="";
$email="";
$batch="";
$mobile="";
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['batch'])) {
$batch = $_POST['batch'];
} else {
$error .= "You didn't type batch. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (!empty($_POST['mobile'])) {
$mobile = $_POST['mobile'];
} else {
$error .= "You didn't type your Mobile Number. <br />";
}
if (empty($error)) {
$success = "<b>Thank you! Your message has been sent!</b>";
}
}
?>
<div id="contactForm">
<?php
if (!empty($error)) {
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
mysql_query("INSERT INTO contact (name,batch,email,mobile)
VALUES('$name','$batch','$email','$mobile') ") or die(mysql_error());
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
?>
This is opposite of what it should be
if (!empty($error)) {
^
// your database stuff here
}
You should run that query when the error is empty, and not when its not empty.
if (empty($error)) {
// now save to database
}
Also go through How can I prevent SQL injection in PHP?
Check the condition on which you are inserting the data in the database. You are checking if (!empty($error)) which should denote that there is an error. Also since $error is a string, I would recommend you to check the values as if(trim($error) != "") rather than using empty()
you should use else if to check each condition..
if(isset($POST['submit'])){
if(empty($_POST['email'])){
$error[] = "email is required";
}
elseif(empty($_POST['name'])){
$error[]= "name is required;";
}
...
else{
$email = $_POST['email'];
$name = $_POST['name'];
// do all the stuff here
}
}
// also correct !empty ()
mysql_query(" INSERT INTO contact (`name`,`batch`,`email`,`mobile`)
VALUES('".$name."','".$batch."','".$email."','".$mobile."');
You need to concatenate the strings. If you put $email in quotes, it will be considered a string and not a variable.

Error while validating numbers in php

I m trying to validate only numbers in php but it is displaying error message.I want user to enter a valid mobile number,batch where only 4 numbers as to be entered. No characters should be entered.Please tell me whats the error in the code.
Here is the code
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['batch'])) {
$batch = $_POST['batch'];
}
if (!preg_match('/^[0-9]+$/', $batch)) {
$error .= "Enter a Valid Number. <br/>";
}
else {
$error .= "You didn't type batch. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (!empty($_POST['mobile'])) {
$mobile = $_POST['mobile'];
}
if (!preg_match('/^[0-9]+$/', $mobile)){
$error .= "Enter A Valid Number. <br/>";
}
else {
$error .= "You didn't type your Mobile Number. <br />";
}
(!preg_match('/^[0-9]{4}$/', $batch)
Use this if you want to validate for only 4 numbers.

Php + mysql insert data securely

i'm worried about the security of my form. The idea is to make a form to participate in a contest in facebok. Basically just firstname, lastname, email. I've been searching through topics and there is a lot of info about security but i can't figure out what is enough security?
I know that there will always be a risk that someone finds a way to abuse the security, but i'd like to find a solution, which blocks the most of them. Also if there are obvious mistakes, please let me know.
Here is my code and all help and guidance is appreciated.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$firstErr = $lastErr = $emailErr = "";
$first = $last = $email = "";
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["first"])) {
$firstErr = "Name is required";
echo "<p>Firstname: $firstErr</p>";
} else {
$first = test_input($_POST["first"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$first)) {
$firstErr = "Only letters and white space allowed";
echo "<p>Firstname: $firstErr</p>";
}
}
if (empty($_POST["last"])) {
$lastErr = "Name is required";
echo "<p>Lastname: $lastErr</p>";
} else {
$last = test_input($_POST["last"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$last)) {
$lastErr = "Only letters and white space allowed";
echo "<p>Lastname: $lastErr</p>";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
echo "<p>Email: $emailErr</p>";
} 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";
echo "<p>Email: $emailErr</p>";
}
}
if ($firstErr == false && $lastErr == false && $emailErr == false) {
$query = "INSERT INTO contactstable (first,last,email) VALUES(:first,:last,:email)";
$statement = $dbh->prepare($query);
$statement->execute(array(
':first'=> $first,
':last'=> $last,
':email'=> $email
));
echo "<p>Thank you for participating!</p>";
}
else {
echo "Fix the missing or incorrect lines.";
}
}
?>
You are using PDO, it already implements the security measures for 1st order injection and when the queries are parametrized the 2nd order also prevented(2nd order injection means data has been cycled through the database once before being included in a query).
But there is no harm if you implements validations for the inputs.

My php validation and form to email go straight to my confirmation page

I have a form, php validation, and send to email. My php validation works fine. My send to email works fine. When I use them both together, they work fine until I add header('Location: http://google.com'); exit(); I am using google.com for because I havent made my confirmation page yet. When I add this line to the php, that's when it goes straight to google.com when I go to my website. Can someone please help? I have been trying to figure out all of this validation and form to email for 2 straight days now, and I cannot figure it out. I know nothing about php. My code is below.
My php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// 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["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"])) {
$email2Err = "It is required to re-enter your email.";
} else {
$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email2)) {
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$commentsErr = "A comment is required.";
} else {
$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service'])) {
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
if (empty($errors)) {
$from = "From: Our Site!";
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to, $subject, $message, $from);
header('Location: http://google.com');
exit();
}
?>
Please someone help me. I have no idea what is wrong.
Ok. I did what you told me Barmar. Not sure if I did it right or not. It solved one problem, but another was created.
I started over with the code that validates and sends the form data to my email. Now I just want to add header('Location: http://google.com '); exit(); ....and it work. Can you tell me what to do? I have no idea what php, so the more specific that you can be, the better.
Here is the php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);
// 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["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"]))
{$email2Err = "It is required to re-enter your email.";}
else
{$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email2))
{
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"]))
{$commentsErr = "A comment is required.";}
else
{$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service']))
{
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to,$subject,$message,$from);
}
?>
The problem is that there's no variable $errors. So if(empty($errors)) is always true, so it goes into the block that sends email and redirects. This happens even if the user hasn't submitted the form yet -- I'm assuming this code is part of the same script that displays the registration form after the code you posted.
You need to make two changes:
The code that sends the email and redirects should be moved inside the first if block, after all the validation checks.
Instead of if(empty($error)), it should check if($nameErr && $emailErr && $email2Err && $commentsErr). Or you should change the validation code to set $error whenever it's setting one of these other error message variables.
I know this isn't a direct answer to your question, but have a look into Exceptions. By having seperate functions for each validation and have them throw an exception when something is wrong, your code will be much cleaner and bugs will have much less room to pop up. Bonus points if you put all the validation functions in a class.
Example: (I renamed test_input() to sanitize_input(), because that's what it does)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try
{
$name = getValidatedName();
$email = getValidatedEmail();
// send email with $name and $email
}
catch (Exception $e)
{
echo '<div class="error">' . $e->getMessage() . '</div>';
}
}
function getValidatedName()
{
if (empty($_POST["name"]))
throw new Exception("Name is required");
$name = sanitize_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name))
throw new Exception("Only letters and white space allowed");
return $name;
}
function getValidatedEmail()
{
if (empty($_POST["email"]))
throw new Exception("Email is required");
$email = sanitize_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // you don't have to reinvent the wheel ;)
throw new Exception("Invalid email format");
return $email;
}

Categories