email validator is not working PHP [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i am new in php and i am working on a login and registration form . I created a function to check if the email address is valid or not even though i did't get any errors but it don't seem to work. It would be a great help if anyone here could take a look at my code.
<?php
$firstname="";
$lastname="";
$email="";
$password="";
$confirm_password="";
$error= array("firstname"=>"",
"lastname" =>"",
"email" =>"",
"password" =>"",
"confirm_password"=>"" );
function correct_email(){
if(!empty($email)){
if(filter_var($email,FILTER_VALIDATE_EMAIL)){
return true;
}else{
echo"your email address is not valid";
}
}
return false;
}
function correct_password(){
global $error;
if(empty($error['password'])){
if(strcmp($_POST['password'],$_POST['confirm_password'])==0){
return true;
}else{
$error['password']="Password didnot match";
$error['confirm_password']="Password didnot match";
}
}
return false;
}
function validate(){
global $error;
$valid= true;
foreach($_POST as $key=>$value){
if(empty($value)){
$valid=false;
$error[$key]="This field is blank";
}
}
return correct_password() && correct_email() && $valid;
}
if($_SERVER['REQUEST_METHOD']=="POST"){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$password=$_POST['password'];
$confirm_password=$_POST['confirm_password'];
if(validate()){
echo "registration succesful";
die;
}
else{
echo "couldnot register";
}
}
?>
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>New Memebers Registration</h1>
<form method="post" action="register.php">
<table>
<tr>
<td>Firstname:</td>
<td><input type="text" name="firstname" value="<?= $firstname ?>">
<?= $error['firstname'] ?> </td>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="lastname" value="<?= $lastname ?>">
<?= $ error['lastname'] ?> </td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" value="<?= $email ?>">
<?= $error['email'] ?> </td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" value="<?= $password ?>">
<?= $error['password'] ?> </td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirm_password"
value="<?= $confirm_password ?>">
<?= $error['confirm_password'] ?> </td>
</tr>
<tr>
<td colspan="2" class="pullright">
<input type="submit" value="Register"> </td>
</tr>
</table>
</form>
</body>
</html>

You don't pass $email to your function so it is not available within your function due to scope. See variable scope to learn more about this.
filter_var() will return false if the email address is blank so you don't need to check that.
You should not echo out anything from your function. Just return true or false and let the code do the error handling.
But if you insist on setting error message in your code you are being inconsistent in your code as you echo an error message here instead of capturing it in your $error array like elsewhere in your code.
You can return true by default and only return false on error which shortens up your code a bit.
Your function:
correct_email($email) {
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error['email'] = "your email address is not valid";
return false;
}
return true;
}
Calling it:
return correct_password() && correct_email($email) && $valid;
I recommend removing any reference to global and pass all needed variables as parameters as using global is considered a bad programming practice.

the variable is outside the function scope.
you need to define the function like:
function correct_email($email)...
when you call it parse email first to validate() then to correct_email:
correct_email($email)
or use the global
correct_email($_POST['email'])

Related

Associative Array check if login combination is correct

This is my very first post and question on this website. I'm working on my school assignment now and I have to check if the login credentials are the same as the ones that are listed in my associative array. I have searched everywhere but I couldn't find an answer. Can someone please tell me how to do this?
This is my PHP code:
// Create associative array
$loginCombinations = array("Lucas"=>"lucas3284", "Bob"=>"bob9584", "Frits"=>"frits1842", "Kees"=>"kees1394", "Sjakie"=>"sjakie1953", "Bas"=>"bas6382", "Peter"=>"peter2391", "Robbie"=>"robbie1289", "Jan"=>"jan1462", "Tim"=>"tim9324");
// Create message (login succesful / login failed)
$message = "";
// Create foreach loop
foreach($loginCombinations as $username => $password)
{
}
and this is my HTML code:
<form action="login.php" method="get">
<table>
<tr>
<td>
</td>
<td>
<?php
echo $message;
?>
</td>
</tr>
<tr>
<td>
<label for="username">username</label>
</td>
<td>
<input type="text" id="username" name="username">
</td>
</tr>
<tr>
<td>
<label for="password">password</label>
</td>
<td>
<input type="password" id="password" name="password">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit">
</td>
</tr>
</table>
</form>
First, change GET method to POST as <form action="login.php" method="POST"> to send the data in request payload rather than as GET parameters for security.
So, you would put if condition in the foreach loop to check and echo success message accordingly.
<?php
$found = false;
foreach($loginCombinations as $username => $password){
if($_POST['username'] == $username && $_POST['password'] == $password){
echo "Yes, user found!!";
$found = true;
break;
}
}
if(!$found){
echo "No user found!!";
}
Update:
Add a name attribute to your submit button say submit like <input type="submit" name="submit">. Now, you will need to add an additional if condition to check if data was actually posted.
<?php
if(isset($_POST['submit'])){
$found = false;
foreach($loginCombinations as $username => $password){
if($_POST['username'] == $username && $_POST['password'] == $password){
echo "Yes, user found!!";
$found = true;
break;
}
}
if(!$found){
echo "No user found!!";
}
}
Update #2:
As pointed out by #Nigel Ren, you can simply do an isset check.
if(isset($loginCombinations[$_POST['username']],$loginCombinations[$_POST['password']])){
echo "user found";
}else{
echo "user not found";
}
As your array is indexed by the user name, there is no need to do a loop. First check if the user name element is set and then check the password for a match...
$userName = $_GET['username'] ?? '';
$message = "";
if ( isset($loginCombinations[$userName]) &&
$loginCombinations[$userName] === $_GET['password']) {
$message = "user login correct";
}
else {
$message = "user login incorrect";
}

Registration redirecting even with validation errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have created a php registration page. Everything is running well. It shows an error when I leave text box empty.
However when I use the action method to redirect the registration page, it's always redirecting, both when I am writing something and when I'm not entering something in the text box.
I want that the page doesn't redirect when the field is empty. I use a boolean and the break method, but nothing is happening.
Can anyone help me here on this issue?
<html>
<?php
include 'header.php';
$nameErr = $emailErr = $genderErr = $passwordErr = $addErr = $phoneErr = "";
$fullname = $email = $gender = $password = $address = $phone = "";
$flag = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
break;
$flag
}
else {
$fullname = test_input($_POST["fullname"]);
}
if (empty($_POST["password"])) {
$passwordErr = " password required";
break;
}
else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
break;
}
else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["address"])) {
$addErr = "Address required";
break;
}
else {
$gender = test_input($_POST["address"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
break;
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone no required";
break;
} else {
$phone = test_input($_POST["phone"]);
}
}
?>
<body>
<br>
<div class="regis_div" >
<form name="myForm" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post" action="thanks.php" >
<table class="table2" border="0" align="center" cellspacing="15" >
<tr>
<td colspan="3"><h1><center>User Registration Form</center></h1></td>
</tr>
<tr>
<td width="291">       Full name:</td>
<td width="150"><input type="text" name="fullname"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $nameErr;?></span></font></td>
</tr>
<tr>
<td>      Password</td>
<td><input type="password" name="password"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td>      Confirm Password</td>
<td><input type="password" name="Confirmpassword"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td>      Email Address:</td>
<td><input type="text" name="email" ></td>
<td><span class="error"><font size="2" color="red">* <?php echo $emailErr;?></span></td>
</tr>
<tr>
<td>      Gender:</td>
<td><input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male</td>
<td><span class="error"><font size="2" color="red">* <?php echo $genderErr;?></span></td>
</tr>
<tr>
<td height="80">      Address:</td>
<td><textarea type="text" name="Address" class="address" rows="4" cols="20" ></textarea></td>
<td><span class="error"><font size="2" color="red">* <?php echo $addErr;?></span></td>
</tr>
<tr>
<td>      Phone No:</td>
<td><input type="text" name="phone"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $phoneErr;?></span></td>
</tr>
<tr>
<td colspan="2"><input class="regbtn2" type="submit" value="Submit" align="center" ></td>
</tr>
</table>
</form>
</div>
</body>
</html>
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
break;
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone no required";
break;
} else {
$phone = test_input($_POST["phone"]);
}
break will only break out of for, foreach, while, do-while and switch structures, not if statements.
It's also unclear exactly which script you believe should be handling your form submission:
<form name="myForm" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post" action="thanks.php" >
If the script you posted above is named form.php, then the above line will produce the following (invalid) markup:
<form name="myForm" form.php method="post" action="thanks.php" >
When submitted, execution will immediately flow to thanks.php and none of your PHP error checking (as posted above) will run. If you want the code you posted above to run, you should change that form tag to this:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
Then, once you're satisfied that your submission has no errors, you can redirect the user to a new page:
header('Location: thanks.php');
You should also note that, when that line is executed, you will loose access to all of your existing POST data, so you must do something with it if you wish to preserve it before redirecting with a header.
However, there's quite a few issues with your code.
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
break; // Already mentioned this line will have no effect
$flag // Why is this line here?
}
How will you know, using your current structure, if any error was encountered? It would have to look like this:
if(isset($nameErr) || isset($passwordErr) || isset($emailErr) || ...)
You can simplify that with an array:
if (empty($_POST["fullname"])) {
$errors['name'] = "Name is required";
// ...
}
// ...
if(count($errors)) {
// Some error occurred, don't redirect
} else {
// ... do something with POST data ...
header('Location: thanks.php');
exit; // Always exit or die after issuing a header redirect
}
And the associated markup:
<?php if(isset($errors['name'])) { ?>
<span class="error">
<font size="2" color="red">*
<?php echo $errors['name']; ?>
</font> <!-- Don't forget to close all of your opened HTML tags -->
</span>
<?php } ?>

Email Validator Problems- Putting it all together

I'm very new to PHP coding.
I've done tons of research to try and help me. As you can imagine I've gotten tons of material for help. The problem is when I'm trying to put it all together.
Specifically here is my problem. I've come across:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "e-Mail is Valid";
} else {
echo "Invalid e-Mail";
}
But I have no idea how to implement it. As it stands now the validator checks the fields before the user has time to imput them..... I'm desperate
I'm sure the solution is really simple, but I've spent hours on this and am really desperate for this problem to be solved already.
Here's a link to the page
Here is the code for the page:
<!DOCTYPE html>
<head>
<meta charset='utf-8'>
<title>AWalsh Photography - Contact Me</title>
<link href="style/main_page.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="email_container">
<h1 class="email_head"> Contact Andrew walsh Photography</h1>
<form id="email_form" name="email_form" method="post">
<table>
<tr>
<td><label for="fname">First Name:</label>
</td>
<td><input type="text" name="fname_input" id="fname_input" /><br>
</td>
</tr>
<tr>
<td><label for="lname">Last Name:</label>
</td>
<td><input type="text" name="lname_input" id="lname_input" /><br>
</td>
</tr>
<tr>
<td><label for="email_input">Your Email:</label>
</td>
<td><input type="text" name="email_input" id="email_input" /><br>
</td>
</tr><tr>
<td><label for="email_conf">Re-enter Email:</label>
</td>
<td><input type="text" name="email_conf" id="email_conf" /><br>
</td>
</tr><tr>
<td>
<label for="message_input">Message </label>
</td><td>
<textarea rows="8" cols="45" id="message_input" name="message_input"></textarea>
</td></tr><tr><td></td>
<td>
<input id="submit"type="submit" value="submit" name="submit"/>
</td></tr>
</table>
</form>
<?php
if($_POST['email_imput'] == $_POST['email_conf']){
//stuff to do on success
echo '<h1>Success!!</h1>';
} else {
//stuff to do on failure
echo '<h1>Sorry, The emails you entered do not match</h1>';
}
$email_imput = $_POST['email_imput'];
if (filter_var($email_imput, FILTER_VALIDATE_EMAIL)) {
echo $email_imput . ' is a valid email address.';
} else {
echo $email_imput . ' is not a valid email address.';
}
$message_imput = $_POST['message_imput'];
$msg = "Email address: $email_imput \n" . "Message: $message_imput";
$to = 'myemail#gmail.com ';
$subject = 'AWP_email';
if (filter_var($email_imput)){
mail($to, $subject, $msg, $email);
}
if (mail($to, $subject, $msg, $email)) {
echo("<p>Message successfully sent! Thanks for submitting your message. We will reply to you as soon as possible</p>");
} else {
echo("<h1>Sorry, There was an error in your imput. Please try again.</h1>");
}
?>
<span class="error"><?=$error;?></span>
<form method="post" action="">
<h1> There was an error with your post</h1>
</form>
</div>
</div>
</body>
</html>
Any input would be amazing. Thank you.
You could add a hidden field into the form and check it's value when it's time to send the email.
if (isset($_POST["some_hidden_field"])) {
// put form validation and sending email here
}
else {
// print the form
}
You should first check whether the page has been submitted or not. You might want to try if ($_SERVER['METHOD'] == 'POST') before making any validations

PHP Code Error. Can't find my logic mistake

Ok. So this is my code below. I'm trying to follow a tutorial on webtuts about validating email. But my sample is not working out. It is supposed to alert the user that it has entered an invalid email. So what my mate did is he created the "show_warning" jquery function to allow me to display my $msg. But it doesn't work. Is my logic wrong?.
<?php
if(isset($_POST['username']) && !empty($_POST['username']) AND
isset($_POST['password']) && !empty($_POST['password']) AND
isset($_POST['email']) && !empty($_POST['email']) AND
isset($_POST['role_id']) && !empty($_POST['role_id']))
{
$username = ($_POST['username']);
$password = ($_POST['password']);
$email = ($_POST['email']);
$role_id = ($_POST['role_id']);
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
{
$msg = 'The email you entered is invalid. Please try again.';
}
else
{
$msg = 'Your account has been made, <br /> please verify by clicking the activation link in your email.';
}
}
?>
======================================
<div id="main-content">
<div id="create-user">
<h1>Create User</h1>
<form action="" method="post">
<table id="userform" width="600px" border=0>
<tr>
<td><label for="username">Username</label>
<input type="text" id="username" name="username" /></td>
<td><label for="password">Password</label>
<input type="text" id="password" name="password" /></td>
</tr>
<tr>
<td><label for="email">Email</label>
<input type="text" id="email" name="email" /></td>
<td><label for="role_id">Role</label>
<select>
<?php $roles = load_roles() ;?>
<?php foreach ($roles as $role): ?>
<option value='<?php echo $role['role_id']; ?>'><?php echo $role['role']; ?></option>
<?php endforeach; ?>
</select></td>
</tr>
<tr>
<td><input type="submit" id="submit" name="save_user" value="Create User"></td>
</tr>
</table>
</form>
</div>
</div>
for validating email php provides
$email="test#gmail.com" //your email to validate here
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "E-mail is valid";
}
else
{
echo "E-mail is not valid";
}
and you must not use eregi. you can use preg_match()
for more validation function follow this link
http://php.net/manual/en/filter.filters.validate.php
eregi() function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
so its would be actual reason
AND preg_match() with the i (PCRE_CASELESS) modifier is the suggested alternative.
as in answer of Yadav Chetan use FILTER_VALIDATE_EMAIL instead those regx
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
{
echo $msg = 'The email you entered is invalid. Please try again.';
}
else
{
echo $msg = 'Your account has been made, <br /> please verify by clicking the activation link in your email.';
}

How to make a PHP Error message popup instead of new page? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Currently on my website I have a form in which once it is submitted, you're taken to a blank screen with the appreciation message.
Instead of moving to a new page, I wish to keep my users on the same page. How might I go about creating a popup and keeping the user within the same page?
You can use javascript validation or HTML5.
If you don't want these ways you can just open a popup window and set your form's target to it. Like this :
<form method="post" action="anything.php" onsubmit="window.open('','my_form_target', 'width=300,height=200', true); this.target='my_form_target';" >
...
try this for validation
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['uname'];
$email = $_POST['email'];
$valid_arr = array();
$error_arr = array();
if($name == ''){
$error_arr['name'] = 'Required';
}
else if(!preg_match('/^[a-zA-A]+$/',$name)){
$error_arr['name'] = 'Please put correct value';
}
else{
$valid_arr['name'] = $name;
}
if($email == ''){
$error_arr['email'] = 'Required';
}
else if(!preg_match('/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
$error_arr['email'] = 'Exm.- john#gmail.com';
}
else{
$valid_arr['email'] = $email;
}
if(count($error_arr) == 0){
header('location: success.php');
}
else{
echo 'Error in Loading';
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<table>
<tr>
<td><label>User Name :</label></td>
<td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
<td class="error"><?php echo $error_arr['name'];?></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
<td class="error"><?php echo $error_arr['email'];?></td>
</tr>
<tr>
<td><input type="submit" name="save" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>

Categories