php email validation not recognizing .com.com - php

Given below is the test code for the issue
If an invalid email with extension .com.com is given it is treated as valid
Please help to resolve the same
Thanks in advance
<?php
if(isset($_POST['submit']))
{
function validate_email($email)
{
$exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*#([a-z0-9]+([._-][a-z0-9]+))+$";
if(eregi($exp,$email))
{
if(checkdnsrr(array_pop(explode("#",$email)),"MX"))
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
$email = $_POST['email'];
print $details= validate_email($email);
}
?>
<form action="" method="post">
<h1> Email </h1>
<input type="email" name="email">
<button type="submit" name="submit"> SUBMIT </button>
</form>

How should it know that that email address is wrong?
A valid email address is already "someone#company"
Where "company" could be your intranet systems hostname. For reasons like that FILTER_VALIDATE_EMAIL doesn't check for a "valid" TLD, as it could not know if it is valid.
As for that it is recommended to NOT write a more specific check on your own, as in a lot of scenarios those checks could render your application useless.

You can use
$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i";
or Just
filter_var('email#email',FILTER_VALIDATE_EMAIL)

You can use this regex :
^([a-z\'0-9\._-]+)#([a-z0-9]+)((\.[a-z0-9]{2,3})(\.[a-z0-9]{2})|(\.[a-z0-9]{2,3}))$
Working well with "john.doe#gmail.com" or "john.doe#domain.co.uk", but it's very difficult to match all the possibilities now too many different tld are availables.
You should try the API of an email verification service.
Regards

Related

Nothing happens when typing a wrong username. what's wrong in my code?

I'm trying to understand what's went wrong with my code. it's a login proccess to cp. you do get the right outcome when writing the correct username (only username yet, just for that test). but you get nothing at all when you don't - nothing I've programmed it to do.
I'm REALLY desperate, tried to solve this the whole night. please help me.
here's the code.
calculations:
if (isset($_POST['connection_made'])) { // is a connection been made? using a hidden input
$form_user = forms_filter($_POST['form_user']); // filter any tags or any unwanted actions first
$form_pass = forms_filter($_POST['form_pass']); // filter any tags or any unwanted actions first
if (strlen($form_user) > 5 AND strlen($form_user) < 16 AND strlen($form_pass) > 5 AND strlen($form_pass) < 16) {
if (login_blank_filter($form_user, $form_pass) == true) { // are those values length shorter than the minimal value or longer?
$user_name = $form_user;
$raw_password = $form_pass;
$user_pass = password_hash($raw_password, PASSWORD_DEFAULT); // generating a hashed and salted password
$cp_validate_login = mysqli_query($data_connection, "SELECT * FROM `admins` WHERE `username` = '$user_name' ");
if (!$cp_validate_login) { die('error: ' . mysql_error()); }
while ($admin_row = mysqli_fetch_array($cp_validate_login)) {
if (mysqli_num_rows($cp_validate_login) == 1) {
echo "you made it.";
echo mysqli_num_rows($cp_validate_login);
}
else {
echo "not yet there.";
echo mysqli_num_rows($cp_validate_login);
}
}
}
else {
header('Location: index.php?login_status=2');
}
}
}
Form:
<?php
if (isset($_GET['login_status'])) {
switch ($_GET['login_status']) {
case 1:
echo "wrong username or password";
break;
case 2:
echo "the inputs has to be filled";
break;
case 3:
echo "username\passwords are too short or too long";
break;
default:
echo "unknown error";
}
}
else {
echo "welcome. log in to the control panel please";
}
?>
</div>
<form name="loginform" method="post" action="index.php" onSubmit="return validateBlank()">
<input type="hidden" name="connection_made" value="">
<div class="login_layout">
<div class="login_right_layout">
user:
</div>
<div class="login_left_layout">
<input class="login_input" name="form_user" type="text">
</div>
<div class="login_right_layout">
password:
</div>
<div class="login_left_layout">
<input class="login_input" name="form_pass" type="password">
</div>
</div>
<input type="submit" value="כניסה" class="login_submit">
</form>
</center>
PLEASE help me. thank you.
First, you are wide open to SQL injection. You need to use prepared statements, rather than concatenating variables into your query. See How can I prevent SQL injection in PHP?.
Second, your code fails because you never make it into the while loop if the username is invalid. That is, if you type a bogus username, this condition is never satisfied:
while ($admin_row = mysqli_fetch_array($cp_validate_login))
So, your if/else logic is never executed.
The solution here is not to try to improve your existing code. It's to stop what you're doing and use an existing authentication (login) library. Security is hard, and proper authentication and authorization is no exception. You should not roll your own security code.

PHP form validation that includes SUBMIT button

I have been trying to find a way to validate email in my PHP code. I can only give you parts of my code cause it is really long. What I want to do is to have a person enter their email address by clicking a submit button and if they have entered their email in an unacceptable format, an error message appears. But my problem is: how can I COMBINE a tag WITH "function validate email($field)"? In other words, I know how to combine (PART A) and (PART B), that is easy enough. But what I really want to do is combine (PART B) with (PART C) and not use (PART A) at all. Is that possible? Can I somehow include "isset" inside "function validate email($field)"? I must have a submit button and I must be able to validate the email.
(PART A) <?php //formtest2.php
if (isset($_POST['email'])) $email = $_POST['email'];
else $email = "(Not entered)";
?>
(PART B) <?php
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
?>
(PART C) <body>
Your email is: $email<br>
<form method="post" action="brownuniversity.php">
What is your email address?
<input type="text" name="email">
<input type="submit">
</form>
</body>
Hi first of all your gonna want to change this whole thing,
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
To this little bit.
function validate_email( $field ){
if (preg_match("/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $field)){
return true;
}
return false;
}
You'll have to do the error messages elsewhere, but this is more portable. ( and I give you a much better Regx for emails ), now you can just do this
if(isset($_POST['email'])){
$email = trim( $_POST['email'] ); //remove any whitespaces from pasting email.
if(validate_email($email)){
//send mail or whatever
}else{
//show errors
}
}
You will still have to check if isset( $_POST['email'] inside the validation isn't really the place to check for it, it should only be concerned with if the data is valid or not, not if there is no data. Also you'll need to check that the form was posted anyway before calling the function and the isset serves both these needs. I updated the answer, you don't really need a validation message on the case that it is not set, because if that is the case they didnt submit the form, it should always be set on form submission.

PHP mail() won't send when included in other PHP file with user input email

I am generating a page of information from a database. I need to send an email with the page content as a reminder. (example here takes input as message)
It takes in an email address and is supposed to send the details to that address.
<div class="container">
<?php
$name = $_GET['info'];
if(isset($name)){
$info = explode('|', $name);
/*****************************************************
open conection to the mySQL database
******************************************************/
....
/*****************************************************
Populate the page
******************************************************/
$sql="Select information from table";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
/*Title*/
echo '<h1>'.$row['post_title'].'</h1><hr>';
/*content*/
echo '<h2>Details: </h2><br>'.$row['post_content'].'<br>';
$content = $row['post_title'];
/*Reminder*/
echo '<div data-role="collapsible">
<h1>Send a reminder</h1>';
include("includes/email_reminder.php");
echo'</div>';
}
/*****************************************************
Close connection
******************************************************/
mysqli_close($con);
} else {
echo'Nothing selected. Go back <br>
<img src="img/icon/Back.png" style="height: 3em" > ';
}
?>
</div>
That creates a form at the bottom of the page to take in the email that needs that needs a reminder.
This is email_reminder.php:
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
{
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback">
</form>
<?php
}
else // the user has submitted the form
{
// Check if the "from" input field is filled out
if (isset($_POST["to"]))
{
// Check if "from" email address is valid
$receivecheck = spamcheck($_POST["to"]);
if ($receivecheck==FALSE)
{
echo "Invalid input";
}
else
{
$to = $_POST["to"]; //receiver
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("$to",$subject,$message,"From: myaddress#mail.com\n");
echo "reminder has been sent";
}
}
}
?>
I have used that form in isolation (just opened email_reminder.php on its own) and it sent emails correctly from whichever email address I used. It just doesn't send when included in the other script.
include(emai_reminder.php); needs single quotes surrounding the file name (and email correctly spelled: include('email_reminder.php');
But, it looks like you need more help than just this. For example, there is no field FROM in your form, although you reference $_POST["from"]. You're running validation against that variable, which doesn't exist, which fails validation, which prevents the else if block from running, which prevents mail() from ever being called.
Several reasons why mailing to different user-defined addresses may not work:
1.) Check the result from the mail() call is TRUE, just to make sure the underlying sendmail (if you are on Linux) did not return an error.
2.) Add additional headers to prevent problems when delivering mails to foreign SMTP hosts, an example may be found on PHP doc for mail()
3.) In some cases (i.e. when using SMTP on Windows) using the PEAR Mail package may solve your problem. It also supports ASMTP and error trapping is much easier compared to the mail() function.

Implement spam-block into contact form 7

I am currently looking into adding a bit of code into both the front end and back end of my form, but I am having trouble figuring out how to do so.
This is the front end code
<li id="user"> <label for="username">Username</label> <input type="text" name="username"> </li>
I will display none that and use it as a honeypot for spam bots.
However, the next bit of code I need to implement is:
<?php if( !isset($_POST['name'])) { die("No Direct Access"); } // Make sure the form has actually been submitted
$name = $_POST['name'];
$email = $_POST['email'];
$spam = $_POST['username']; // This is our Honeypot field if($spam) { // If the Honeypot field has been filled in die("No spamming allowed bitch!"); }
else { // Process the form like normal } ?>
Now the point being is $name and $email are dynamic fields in contact form 7. What could I do to make those avail in contact form 7 as var for this script?
Thanks in advance!
Inside of /contact-form-7/includes/classes.php you can add your code and mark it as spam if you want.
Line 432 under function spam() add lines that follow something similar to this:
if (isset($_POST['username'])) {
$spam = true;
}

How would I go about making this error message appear when form field is not right?

I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:
if(isset($_POST['submit'])) {
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
$error = "";
} else {
$error = "Please fill in the required fields.";
}
}
In the form, I have a span class like so:
<span class="error">'.$error.'</span>
I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?
Thanks so much for any help or tips!
In order to process the form while staying on the page, you will need to incorporate some AJAX. The easiest way to do this is to use a framework of some sort (recommend jQuery). This should give you some insight into how to develop such functionality. If you get stuck, we're here to help.
http://api.jquery.com/jQuery.post/
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script. You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.
Are you echoing out the error message within the span, or is all that output being placed after an echo statement?
echo '<span class="error">'.$error.'</span>'
Or, if not in the PHP context outside of script
<span class="error"><? echo $error; ?></span>
Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.
You don't need any AJAX.
$error = '';
if (isset($_POST['submit'])) {
if ( <<< insert check for required fields >>> ) {
// handle form, send mail, etc
// you may want to redirect on success to prevent double posting
} else {
$error = "Please fill in the required fields.";
}
}
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.
<?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
} else {
$error = "Please fill in the required fields.";
}
}else{ ?>
<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
<span class="error><?php echo $error; ?></span>
Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
<input type="submit" value="Submit Email"/>
</form></div>
<?php } ?>
When I handle form validations, I tend to create an array to hold the error messages, like so:
<?php
$error = array();
if( $POST ){
# Form is Submitted
if( /* TRUE if "email" is empty */ ){
$error['email'] = 'Please provide an Email Address';
}elseif( /* TRUE if "email" is not a valid address */ ){
$error['email'] = 'Please provide a Valid Email Address';
}elseif( /* TRUE if "email" is already associated with a User */ ){
$error['email'] = 'The Provided Email Address is Already Taken';
}
...
if( count( $error )==0 ){
# No Error has been Recorded
# Do Successful Things
}
} /* Closing if( $_POST ){ */
Then within the presentation/display section, I have something like:
<?php if( count( $error )>0 ){ ?>
<div id="error">
The following Errors have occurred:
<ul>
<?php foreach( $error as $k => $v ){ ?>
<li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
And within the form, something like:
<input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />
This means that:
Customised, multi-tiered error messages can be recorded.
A summary of the error messages can be shown.
Fields associated with the error messages can be marked.
Has worked well in my experience thusfar.
Yep, I think You have two methods to do that, as already explained above...
When the form is submitted to the same page (itself) using *$_SERVER['PHP_SELF']*, you can check weather each posted field is empty using empty() function. Then if they are not filled then set the variable $error and then use echo $error; at the span of error... If no any error you can assign the default message at the $error instead of the error... It should do what you need...
You can use AJAX and send a request to the page and set the error message. Then the page is not fully refreshed as it was before, but only the element you wanted to refresh. This is fast, but in most of the cases, first method is preferred, unless AJAX is a need..
What exactly you want to do? If you specify what's your actual need, it is possible to provide some sample code... (First method is already discussed)
Thank You.
ADynaMic
My suggest is to use ajax call when submit,
according to the answer come back, you update the span of error.
you can find a lot of examples in web like
http://jqueryfordesigners.com/using-ajax-to-validate-forms/
http://www.the-art-of-web.com/javascript/ajax-validate/

Categories