Error while validating numbers in php - 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.

Related

php validate post request before add to data base

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

PHP Form validation using 'if'

I'm currently building a very small 'contact' form for use on a personal site.
The form works, and each validation 'if' statement works individually, however, if for example I input a valid email address and phone number but leave the message blank, the email still sends and I get the success message.
My guess would be to include the small 'if' statements into the one checking whether my required fields are not empty, though i'm not sure how to do this correctly as it is nesting multiple 'if's into one.
Cheers
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
?>
<!-- Display red error box or green success box depending on which is true -->
<?php if(!empty($errors)): ?>
<div class="validationbox | errorsbox">
<?php echo $errors; ?>
</div>
<?php elseif(empty($errors)): ?>
<div class="validationbox | successbox">
<?php echo $success; ?>
</div>
<?php
$message = ''; // Blank message to start with so we can append to it.
// Construct the message
$message .= "
Name: {$_POST['thename']};
Email: {$_POST['email']};
Number: {$_POST['number']};
Enquiry-type: {$_POST['enquiry-options']};
Message: {$_POST['comments']};
";
// test#testdomain.com
$to = 'test-email-deleted-for-stackoverflow';
$subject = 'Message from Portfolio';
$from = $_POST['thename'];
// YourSite#domain.com
$fromEmail = 'test-email-deleted-for-stackoverflow';
$header = 'From: ' . $from . '<' . $fromEmail . '>';
mail($to,$subject,$message,$header);
?>
<?php endif; ?>
<?php endif; ?>
Your problem is that you are resetting $errors back to '' each time one of your validation conditions passes:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
You shouldn't do that, just leave error messages to whatever it previously was. This way, when you get to the end, $errors will contain a string of all the error messages combined. Since there could be multiple messages, you may want to put a break a the end of each one:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.<br>";
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address<br>";
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number<br>";
}
In the case of email, you may want to only display the 'invalid email address' only when something was actually filled in, so you could also check to ensure there is something in there, before you determine if the format is valid or not:
if (!empty($email) && !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
Based on the information Supplied, i think you should use a complex if-elseif-else statement like so:
`if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
} `
in your particular case:
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors = 'Error:invalid email';
}elseif(!preg_match("/^\(?0( *\d\)?){9,10}$/", $number){
$errors .= "Error: Invalid phone number";
} else {
//Do this on successful validation comes here
}
try below code it helps you.
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
}
?>

Form validation in php is not working properly

Can anyone tell me what wrong i am doing here ? Error shows only if the First name is blank, for the rest (e.g lastname/email/body) it's not working. EMail validation also not working.
$error = "";
if (empty($fanme)) {
$error = "First name must not be empty !";
}
elseif (empty($lname)) {
$error = "Last name must not be empty !";
}
elseif (empty($email)) {
$error = "email must not be empty !";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Invalid Email Address !";
}
elseif (empty($body)) {
$error = "Message field not be empty !";
}
else {
$msg = "ok";
}
}
if (isset($error)) {
echo "<span style='color:red'>$error</span>";
}
if (isset($msg)) {
echo "<span style='color:green'>$msg</span>";
}
It looks like you misspelled "$fname" in line 2 of your code above.

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.

Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?

I have:
if(isset($_POST['submit'])) {
if (empty($name)) {
echo'<span class="error">ERROR: Missing Name </span><br/>';
} else if(empty($phone) || empty($email)) {
echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
} else if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}
How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.
Any ideas? Thank you
You could collect all errors in an array like this:
if (isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo 'There were some errors: ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
With this you can check all requirements and report all errors and not just the first one.
use:
$error = 0;
if(empty($var1)){ $error = 1; }
if(empty($var2)){ $error = 1; }
if(empty($var3)){ $error = 1; }
if(empty($var4)){ $error = 1; }
if(empty($var5)){ $error = 1; }
if($error > 0)
{
// Do actions for your errors
}
else
{
// Send Email
}
you can use try...catch statements for error checking like this.
whenever you encounter a condition where an error should be generated, you can use throw new Exception clause.
Use a dirty flag. Check them all and append the message to the dirty variable.
Try this:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = 'Missing Name';
}
if(empty($phone) || empty($email)) {
$errors[] = 'You must insert a phone number or email';
}
if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
$errors[] = 'Please Insert a valid Email';
}
if (!empty($errors)) {
for ($i = 0; i < count($errors); $i++) {
echo sprintf('<span class="error">ERROR: %s</span><br/>', $errors[$i]);
}
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}
if(isset($_POST['submit'])) {
$valid = true;
if (empty($name)) {
echo'<span class="error">ERROR: Missing Name </span><br/>';
$valid = false;
}
if(empty($phone) || empty($email)) {
echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
$valid=false;
}
if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
$valid = FALSE;
}
if($valid) {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}

Categories