How to validate email input? [duplicate] - php

This question already has answers here:
How can I validate an email address using a regular expression?
(79 answers)
Closed 9 years ago.
I'm using the WordPress API to create an options page. One of the inputs need to have an email entered. I need to write a function that will validate the email entered and return it.
function nl_validate_settings( $input ) {
if ( $field_args = array( 'type' => 'email' ) ) {
foreach( $input as $email ) {
if ( ! preg_match( '/^[A-Za-z0-9!#$%&\'*+\/=?^_`{|}~-]+#[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+[A-Za-z]$/', $email ) ) {
$email = "Invalid email address!";
}
}
return $email;
}
}
This isn't working and I don't know what I am doing wrong. It doesn't save emails when an email is entered correctly.
I've checked other answers on StackOverFlow but couldn't find anything that would fix the problem. Your help would be appreciated!
I don't know how to format it

I would use filter_var and use a combination of both the Sanatize and Validation
$email = $_POST['email'];
$clean_email = filter_var($email, FILTER_SANITIZE_EMAIL);
if( filter_var($clean_email, FILTER_VALIDATE_EMAIL) )
{
//Case if Email is valid
}
else
{
//Handle the case the email is invalid
}

Related

checking if email and confirm email fields are the same using php

I would like to confirm that the email field and confirm email field match each other in my html form before submitting the form to the database, i have done the following but it doesn't seem to work:
<?php
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'][] = "Invalid email address";
}
if ($_POST['email'] != $_POST['confirmemail']) {
$_SESSION['error'][] = "Email addresses do not match";
}
else {
this is followed by the script to submit the form to the database which works fine. Any suggestions would be welcome, many thanks
There might be whitespace issue causing your comparison to fail. try trimming your inputs before comparison.
$email = trim( $_POST['email'] );
$confirmEmail = trim( $_POST['confirmemail'] );
if ($emsil != $confirmEmail ) {
$_SESSION['error'][] = "Email addresses do not match";
}

Secure a contact form from scratch in Wordpress

I am currently creating a website with Wordpress, I am creating my theme and I am not using jQuery. I need to introduce a simple contact form, which sends an email on submission and all plugins need jquery to work.
Is it safe to create a contact form that sends an email? Is there a risk of SQL injection since I do not query the database on submission?
I have very little security skill, any information or clarification will be welcome
So for example something like:
$name = "{$_POST['message_name']} {$_POST['message_lastname']}"; // I like to combine first and lastname in to 1 variable.
$email = $_POST['message_email'];
$website = $_POST['message_url'];
$message = $_POST['message_description'];
if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
$response = form_validation_response( 'error', $email_invalid );
} else {
if ( empty( $name ) || empty( $message) ) {
$response = form_validation_response( 'error', $missing_content );
}
}
// The most simple check you can do is make sre that the fields are NOT empty.
The form_validation_response method is a simple function which you can use to return error message:
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
function form_validation_response( $type, $message ) {
$class = 'px-2 py-1 mb-6 rounded-md' // These are tailwind classes, but it could be bootstrap
if ( $type == 'success' ) {
$class .= "border border-green-800 text-green-700";
} else {
$class .= "border border-redish text-redish";
}
return "<div class='{$class}'>{$message}</div>";
}
The example above is used to validate the email, but you can also make sure that the fields are actually submitted, before even starting the validation process:
If you're not familiar with creating a "secure" php form I would advice you to use a plugin for this.
If your "allowed" to install plugins, then have a look "form plugins" like:
WPForms (https://wpforms.com/)
Gravity Forms (https://www.wpbeginner.com/refer/gravityforms/)
Contact Form 7 (https://wordpress.org/plugins/contact-form-7/)
This is just a few of the form plugins that are available. Depending on your need/budget you should then make a decision which plugin fits the best (some are free, freemium, premium etc.).

What's the best way to validate and sanitize forms for email? [duplicate]

This question already has answers here:
How to validate an email address in PHP
(15 answers)
Closed 7 years ago.
I have a form where I ask for information, but some (such as email) is not required. When the form for email is not empty, I'd like the email to be validated and sanitized. My current method only submits the data that is not empty. What's the most effective way to do the validation and sanitization?
Current method
if (empty($_POST["S_Email"])) {
$S_Email = "";
} else {
$S_Email = $_POST["S_Email"];
}
You're looking for PHP Validate Filters:
if (empty($_POST["S_Email"])) {
//No email address POSTed through
$S_Email = "";
} else {
//Email address POSTed
$S_Email = $_POST["S_Email"];
//Validate email
if(!filter_var($S_Email, FILTER_VALIDATE_EMAIL) === false){
//Email is valid
} else {
//Email is invalid
}
}

how to validate email address domain using preg match [duplicate]

This question already has answers here:
How to validate an Email in PHP?
(7 answers)
Closed 9 years ago.
i want to validate the email address domain using pregmatch. also the valid edu domain i inserted in email list array so when user enter the email address that entry first check in email list array. if it is available then it is validate. i am doing validation part on server side.. any help is appericiated. thanks in advanced...
<?php
$email = $_POST['email']; // get the email value
$email_exp = explode("#",$email); // split email
$email_name = $email_exp[1]; // get the domain of email address
$email_list = array("berkely.edu","ucfs.edu","udef.edu","ucms.edu","ucef.edu"); // valid edu domain
for($i=0;$i<sizeof($email_list);$i++)
{
if(in_array($email_name,$email_list))
{
if (preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email_name))
{
// validate email
}
}
}
Use filter_var, and replace the preg_match call with it.
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == TRUE) {
// email is valid
}
So, the updated code will be:
<?php
$email = $_POST['email']; // get the email value
$email_exp = explode("#",$email); // split email
$email_name = $email_exp[1]; // get the domain of email address
$email_list = array("berkely.edu","ucfs.edu","udef.edu","ucms.edu","ucef.edu");
$email_is_valid = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == TRUE;
if($email_is_valid && in_array($email_name,$email_list) ) {
// email is valid for your purposes
}

function eregi() is deprecated in email validation [duplicate]

This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 9 years ago.
Hi ı know that we do not eregi but preg_match but when ı change only eregi code it doesnt work, how can ı change the code below please just a little help, ı am a newbie
function verify_valid_email($emailtocheck)
{
$eregicheck = "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+#([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.)+[a-zA-Z]{2,4}\$";
return eregi($eregicheck, $emailtocheck);
}
function verify_email_unique($emailtocheck)
{
global $config,$conn;
$query = "select count(*) as total from members where email='".mysql_real_escape_string($emailtocheck)."' limit 1";
$executequery = $conn->execute($query);
$totalemails = $executequery->fields[total];
if ($totalemails >= 1)
{
return false;
}
else
{
return true;
}
}
If you need to validate e-mail addresses, you can look at this page which provides a working example using only filter_var() :
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
};
So in your code, you should just drop all the regex/eregi stuff and use this instead :
return filter_var($emailtocheck, FILTER_VALIDATE_EMAIL);
If you want to do it this way, you can base yourself on the following methods:
<?php
$email = \"abc123#somewhere\"; // Invalid email address
//$email = \"somebody#somesite.com\"; // Valid email address
// Set up regular expression strings to evaluate the value of email variable against
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
// Run the preg_match() function on regex against the email address
if (preg_match($regex, $email)) {
echo $email . \" is a valid email. We can accept it.\";
} else {
echo $email . \" is an invalid email. Please try again.\";
}
?>
or:
$string = "$emailtocheck";
if (preg_match(
'/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/',
$string)) {
echo "Successful.";
}
or:
<?php
$email = "abc123#sdsd.com";
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
echo $email . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
?>
Source: https://stackoverflow.com/a/13719991/1415724
or:
<?php
// check e-mail address
// display success or failure message
if (!preg_match("/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*#([a-zA-Z0-9_-
])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/", $_POST['e-mail'])) {
die("Invalid e-mail address");
}
echo "Valid e-mail address, processing...";
?>
Source: http://www.techrepublic.com/article/regular-expression-engine-simplifies-e-mail-validation-in-php/
Plus, you can try what André Daniel wrote as an answer as well. You have many choices.

Categories