email validation in php - php

I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />

Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)

instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error

You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {

For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');

How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.

Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}

function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}

Related

How to make a 2nd check after first row of validations

I have am trying to re-create a form register validation that I seen a few weeks ago but unable to figure it out.
I want to perform one last check after the first 3 checks then display the message
validation code
public function validateSignup(): bool
{
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
return empty($this->errors);
}
This works great for the validation requirements but I want to add another step, to check if email or username is taken, I know how to do this traditionally but wanted to make it different without giving information away.
I have a Helper to tell me if an email is in the database called alreadyExists
what I am trying to accomplish is a 2nd check after that
Example
public function validateSignup(): bool
{
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
return empty($this->errors);
## after it checks validation with no errors check if already exists
if ($this->name) Helpers::alreadyExists("user", "name", $this->name) {
$this->errors['name'] = "Unable to register user with provided data.";
}
return $this->errors;
}
public function validateSignup(): bool {
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
If(count($this->errors) > 0) {
return empty($this->errors);
}
## after it checks validation with no errors check if already exists
if ($this->name) Helpers::alreadyExists("user", "name", $this->name) {
$this->errors['name'] = "Unable to register user with provided data.";
}
return empty($this->errors);
}

Variable always being set to 0 despite conditional blocks

The following block of code is an attempt to give some feedback for what a user may be inputting incorrectly and that side of it is working alright.
The part I am having trouble with is the else block. It seems to always set the $MaxNum variable to 0. If I remove the declaration from the else block it works fine, although obviously doesn't allow my code above to validate the input. I am probably overlooking something quite basic so any help would be great.
global $MaxNum, $TheNum;
if (isset($_POST['Submit'])) {
if (empty($_POST['maxnum'])){
$error[] = "<p>Please enter at least something!";
if($_POST['maxnum'] == 0){
$error[] = "<p>Zero doesn't count!";
}
}
if (!is_numeric($_POST['maxnum'])){
$error[] = "<p>You didn't enter a number!";
}
if (is_numeric($_POST['maxnum'])){
if(($_POST['maxnum'])>2147483647){
$error[] = "<p>2.14 Billion jellybeans is a little excessive, right?";
}
}
else{
$MaxNum = $_POST['maxnum'];
}
}
Some tips:
Try to use functions and early returns in your code, it makes your flow easier.
Try to use less nested if statements and use else if
An example with function and early returns:
global $MaxNum, $TheNum;
function handleFormSubmit(): string
{
if (!isset($_POST['Submit']) || !isset($_POST['maxnum'])) {
return "<p>Please enter at least something!</p>";
}
if(empty(['maxnum'])) {
return "<p>Please fill in a number</p>!";
}
if($_POST['maxnum'] == 0) {
return "<p>Zero doesn't count</p>!";
}
if (!is_numeric($_POST['maxnum'])) {
return "<p>You didn't enter a number!";
}
if (is_numeric($_POST['maxnum']) && $_POST['maxnum'] > 2147483647) {
return "<p>2.14 Billion jellybeans is a little excessive, right?";
}
$MaxNum = $_POST['maxnum'];
return '';
}
$errorMessage = handleFormSubmit();
Used #robbert van den Bogerd's tips to clean up my if statements and then implemented that. Still had the issue of the input being passed as there was nothing stopping that.
Created a new variable called $ValidInput and used it to hold a bool.
Through the checking I set it to False if it met any conditions.
Then at the end of the checks I attach the input to $MaxNum if $ValidInput remains True through the checking, if it made it to that point and was True it must meet our requirements.
global $MaxNum, $TheNum, $ValidInput;
$ValidInput = True;
if (isset($_POST['Submit'])) {
if (empty($_POST['maxnum'])) {
$error[] = "<p>Please enter at least something!</p>";
$ValidInput = False;
}
if(empty($_POST['maxnum']) && (!is_numeric($_POST['maxnum']))) {
$error[] = "<p>Please enter a number!</p>";
$ValidInput = False;
}
if($_POST['maxnum'] == 0) {
$error[] = "<p>Zero doesn't count!</p>";
$ValidInput = False;
}
if (!is_numeric($_POST['maxnum']) && (!empty($_POST['maxnum']))) {
$error[] = "<p>That's not a number!</p>";
$ValidInput = False;
}
if (is_numeric($_POST['maxnum']) && $_POST['maxnum'] > 2147483647) {
$error[] = "<p>Anything over 2.14 Billion jellybeans is a little excessive, right?";
$ValidInput = False;
}
if($ValidInput == True){
$MaxNum = $_POST['maxnum'];
}
}

PHP - Check if one of two form fields is filled?

My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.

I Have A Registration Form That Is Kicking Back Custom Made Errors Before Submission

I'm working on a registration for my classifieds (via a tutorial) but I'm having problems. For some reason, just visiting this page: http://classifieds.your-adrenaline-fix.com/register.php
will generate the 2 custom errors you'll see in a red box above the registration form BUT the form hasn't even been submitted yet so I don't know why this is happening. If anyone could shed some light on this I'd be most appreciative and I thank you all in advance!!
(I've been staring at it for hours)
Here's the code that validates and submits the form data;
<?php
if(empty($_POST) === false) {
$VisitorsFirstName = $_POST['First_Name'];
$VisitorsLastName = $_POST['Last_Name'];
$VisitorsEmail = $_POST['E_mail'];
$VisitorsPassword = $_POST['Pass'];
$RequiredFlds = array('First_Name', 'Last_Name', 'E_mail', 'Pass', 'PassAgain');
foreach($_POST as $key=>$value) {
if(empty($value) && in_array($key, $RequiredFlds) === true) {
$Err[] = 'All Fields Are Required';
break 1;
}
}
if(empty($Err) === true) {
if(email_exists($VisitorsEmail) === true) {
$Err[] = 'The Email Address \''. $VisitorsEmail. '\' Is Already In Use.';
}
if(strlen($VisitorsPassword) < 4) {
$Err[] = 'Please Select A Password of At Least 4 Characters.';
}
if($_POST['Pass'] !== $_POST['PassAgain']) {
$Err[] = 'Passwords Do Not Match.';
}
if(filter_var($VisitorsEmail, FILTER_VALIDATE_EMAIL) === false) {
$Err[] = 'A Valid Email Address is Required';
}
}
}
if(isset($_GET['success']) && empty($_GET['success'])) {
echo 'You Have Now Been Registered and Can Proceed to Creating Your First Ad<br>(Use the Email and Password That You Registered With to Login)';
} else {
if(empty($_POST) === false && empty($Err) === true) {
$register_data = array (
'VisitorsFirstName' => $_POST['First_Name'],
'VisitorsLastName' => $_POST['Last_Name'],
'VisitorsPassword' => $_POST['Pass'],
'VisitorsEmail' => $_POST['E_mail'],
'Notify' => $_POST['Notify']
);
register_func($register_data);
header('Location: register.php?success');
exit();
} else if(empty($Err) === false) {
echo output_error($Err);
}
}
?>
Upon putting just the code you provided on my own server by itself, it works as designed. It isn't running the top block of code, because the $_POST variable is empty. Try outputting the contents of $_POST at the top of the file so you can figure out why it isn't empty.
print_r($_POST);
Try this:
if(!empty($_POST['First_Name']) && !empty($_POST['Last_Name']) && !empty($_POST['E_mail']) && !empty($_POST['Pass'])){
....
}
OR
try isset($_POST['First_Name'])......
This works fine for me!
You could instead check if the submit button was pressed. Like this:
if (isset($_POST['submit']) {
// get the post values
}
This way you could eliminate the script launching before the form was actually submitted. Right now it seems to run as soon as I visit the page.

PHP contact form, am I doing it wrong?

I'm learning PHP and I'm trying to write a simple email script. I have a function (checkEmpty) to check if all the forms are filled in and if the email adress is valid (isEmailValid). I'm not sure how to return true checkEmpty funciton. Here's my code:
When the submit button is clicked:
if (isset($_POST['submit'])) {
//INSERT FORM VALUES INTO AN ARRAY
$field = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($field);
checkEmpty($name, $email, $message);
function checkEmpty($name, $email, $message) {
global $name_error;
global $mail_error;
global $message_error;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$name_error = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$mail_error = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$mail_error = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$message_error = "<span class='error_text'>* Please enter your message</span>";
}
}
// This function tests whether the email address is valid
function isValidEmail($email){
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (eregi($pattern, $email))
{
return true;
} else
{
return false;
}
}
I know I shouldn't be using globals in the function, I don't know an alternative. The error messages are display beside each form element.
First of all, using global is a sin. You are polluting global namespace, and this is bad idea, except little ad-hoc scripts and legacy code.
Second, you are misusing isset - for two reasons:
a ) in given context you pass variable $name to function, so it is always set
b ) empty checks whether variable is set or not
Third, you should separate validation from generating html.
Fourth, you can use filter_var instead of regular expression to test if mail is valid.
Last, your code could look like that:
<?php
if (isset($_POST['submit'])) {
$fields = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($fields);
$errors = validateFields($name, $email, $message);
if (!empty($errors)){
# error
foreach ($errors as $error){
print "<p class='error'>$error</p>";
}
} else {
# all ok, do your stuff
} // if
} // if
function validateFields($name, $email, $post){
$errors = array();
if (empty($name)){$errors[] = "Name can't be empty";}
if (empty($email)){$errors[] = "Email can't be empty";}
if (empty($post)){$errors[] = "Post can't be empty";}
if (!empty($email) && !filter_var($email,FILTER_VALIDATE_EMAIL)){$errors[] = "Invalid email";}
if (!empty($post) && strlen($post)<10){$errors[] = "Post too short (minimum 10 characters)";}
# and so on...
return $errors;
}
First of all, you should really re-think your logic as to avoid global variables.
Eitherway, create a variable $success and set it to true in the top of your functions. If any if statement fails, set it to false. Then return $success in the bottom of your function. Example:
function checkExample($txt) {
$success = true;
if (isset($txt) === true && empty($txt) === true) {
$error = "<span class='error_text'>* Please enter your example text</span>";
$success = false;
}
return $success;
}
I'm not sure this is what you want, the way I see it, you want $mail_error, $message_error and $name_error to be accessible from outside the function. If that's the case, what you need is something like this:
function checkEmpty($name, $email, $message) {
$results = false;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$results['name_error'] = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$results['mail_error'] = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$results['mail_error'] = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$results['message_error'] = "<span class='error_text'>* Please enter your message</span>";
}
return $results;
}
$errors = checkEmpty($name, $email, $message);
now you can test for errors
if($errors){
extract ($errors); // or simply extract variables from array to be used next to form inputs
} else {
// there are no errors, do other thing if needed...
}

Categories