function sending email twice - php

I have the following function sending an email twice (and I believe running if($result) twice).
it is called on a separate page :
<?php $User = new User();
$User->ValidReg();
$valid = $User->ValidReg();
if ($valid === false) {
Here is the function in its class:
public function ValidReg() {
if ( !empty($_POST['username'])
&& !empty($_POST['password'])
&& !empty($_POST['email'])
&& !empty($_POST['state'])) {
//valid ?
$valid = true;
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$state = mysql_real_escape_string($_POST['state']);
$checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");
if(mysql_num_rows($checkusername) == 1) {
echo "<div id='shopperlogin1'><p>Sorry, that username is taken.<br /> Please go back and try again.</p></div>";
}
else {
//test
$confirm_code=mysql_real_escape_string(md5(uniqid(rand())));
$sql="INSERT INTO temp_users (
confirm_code, Username, Password,
EmailAddress, FirstName, LastName, State)
VALUES (
'$confirm_code', '$username', '$password',
'$email', '$firstname', '$lastname', '$state')";
$result=mysql_query($sql)
or die ("Query failed: " . mysql_error() . " Actual query: " . $query);
// if suceesfully inserted data into database, send confirmation link to email
if ($result) {
// send e-mail to ...
$to=$email;
// Your subject
$subject="Your confirmation link here";
// From
$header="blahblah#blahbalh.com";
// Your message
$message="Your Comfirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.employeediscounted.com/secret/login.php?passkey=$confirm_code";
// send email
$sentmail = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "<div id='emailmsg'>Not found your email in our database.</div>";
}
// if your email succesfully sent
if($sentmail){
echo "<div id='emailmsg'>Your Confirmation link Has Been Sent To Your Email Address.</div>";
}
else {
echo "<div id='emailmsg'>Cannot send Confirmation link to your e-mail address.</div>";
}
}
}
else {
$valid = false;
}
return $valid;
}

Either I'm missing something, or you're simply calling the function twice:
$User->ValidReg();
$valid = $User->ValidReg();
So, yes, you will send two emails!
(Were you expecting the second call to fail because the user already exists? It won't because you're using two different tables, users vs. temp_users.)

Related

Trying to set up register form with php & msql

i made simple form for register and connect it to database.
If i sign up for the first time, it allowed me to login and go to main page.
however after i log out and trying to login again it always shows "Incorrect password or email" even i put everything correctly.
tried to reset password, password successfully reset but when i try to login it just showing me same error again.
heres the register php code that im using
//if user signup button
if(isset($_POST['signup'])){
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
if($password !== $cpassword){
$errors['password'] = "Confirm password not matched!";
}
$email_check = "SELECT * FROM usertable WHERE email = '$email'";
$res = mysqli_query($con, $email_check);
if(mysqli_num_rows($res) > 0){
$errors['email'] = "Email that you have entered is already exist!";
}
if(count($errors) === 0){
$encpass = $password;
$code = rand(999999, 111111);
$status = "notverified";
$insert_data = "INSERT INTO usertable (name, email, password, code, status)
values('$name', '$email', '$encpass', '$code', '$status')";
$data_check = mysqli_query($con, $insert_data);
if($data_check){
$subject = "Email Verification Code";
$message = "Your verification code is $code";
$sender = "From: blahblah#example.com";
if(mail($email, $subject, $message, $sender)){
$info = "We've sent a verification code to your email - $email";
$_SESSION['info'] = $info;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header('location: user-otp.php');
exit();
}else{
$errors['otp-error'] = "Failed while sending code!";
}
}else{
$errors['db-error'] = "Failed while inserting data into database!";
}
}
}
And this is login php script im using
//if user click login button
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$check_email = "SELECT * FROM usertable WHERE email = '$email'";
$res = mysqli_query($con, $check_email);
if(mysqli_num_rows($res) > 0){
$fetch = mysqli_fetch_assoc($res);
$fetch_pass = $fetch['password'];
if(password_verify($password, $fetch_pass)){
$_SESSION['email'] = $email;
$status = $fetch['status'];
if($status == 'verified'){
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header('location: index.php');
}else{
$info = "It's look like you haven't still verify your email - $email";
$_SESSION['info'] = $info;
header('location: user-otp.php');
}
}else{
$errors['email'] = "Incorrect email or password!";
}
}else{
$errors['email'] = "It's look like you're not yet a member! Click on the bottom link to signup.";
}
}
When you register new user from your register page, you store plain password into your usertable. Suppose, when you put password = 123, it will store 123 into your password column in your usertable.
But when you try to login with same password 123, your login page logic say the password should be verify with password_verify method.
This method check the password with Hashing algorithm. That's why you are seeing incorect message. You may change the login page logic
From if(password_verify($password, $fetch_pass)) to if($password == $fetch_pass)
Or use properly password_verify method.

What do I have to do to my code so it will only create the account if the email doesn't already exist in the Database? [duplicate]

This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 8 years ago.
<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
while ($myrow = mysql_fetch_array($result)) {
if ($email == $myrow['email']) {
$errorMessage = "Account with that email already exists";
} else {
$errorMessage = "Email doesn't match!";
}
}
if ($_POST['submit']) {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}
?>
When I fill in the form and hit submit it just inserts into the database even though the emails are the same. I tried putting the if statement with the submit button into the while loop but that didn't work either.
Use mysql_num_rows function to check weather the user already exist on the database or not. Use the code below
<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
if(mysql_num_rows($result)==0){
if ($_POST['submit']) {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}
}
else
{
echo "the user with this email address already exist";
}
?>
Hope this helps you
You could change your condition to check whether or not the error message has been filled:
if ($_POST['submit'] && $errorMessage == "Email doesn't match") {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}

unknown column 'email' in where clause

I have problem with this code. It gives me 'Unknown column 'email' in where clause.
I tried almost everything, but I don't know what is the problem. I am beginner so please be gentle :)
Any ideas how to solve it?
Thanks a lot
session_start();
include('connect.php');
if(isset($_POST['submit']))
//when isn't username in form
if($_POST['firstname'] == '')
{
$_SESSION['error']['firstname'] = 'First name is required';
}
if($_POST['surname'] == '')
{
$_SESSION['error']['surname'] = 'Surname is required';
}
//when email isn't in form
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = 'Email is required';
}
//check if is email in correct format
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//email is in correct format and exist?
$email = $_POST['email'];
$sql1 = "SELECT * FROM users WHERE email = '$email'";
$result1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
if(mysqli_num_rows($result1) > 0)
{
$_SESSION['error']['email'] = 'Email is already used';
}
}
else
//error for wrong format of email
{
$_SESSION['error']['email'] = 'Your email is in wrong format';
}
//when isn't password in form
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = 'Password is required';
}
//when is error -> registration form
/*if(isset($_SESSION['error']))
{
header("Location: index.php");
exit();
}
else
*/
{
$firstname = mysqli_real_escape_string($connect,$_POST['firstname']);
$surname = mysqli_real_escape_string($connect,$_POST['surname']);
$email = $_POST['email'];
$password = mysqli_real_escape_string($connect,$_POST['password']);
$phone_number = mysqli_real_escape_string($connect,$_POST['phone_number']);
$note = mysqli_real_escape_string($connect,$_POST['note']);
$sql2 = "INSERT INTO users (firstname, surname, email, phone_number, note, password) VALUES ('$firstname', '$surname',
'$email', '$phone_number', '$note','$password')";
$result2 = mysqli_query($connect, $sql2) or die('Error: ' .mysqli_error($connect));
the column name email may be wrong or does not exist in the data base use the same column name as defined in the data base

null values submitted to mysql database

I am trying to make a user system for my website but having some trouble with submitting it. It always submit a 0 to the database for everything. I have read on w3schools about global and local variables and I think this may be my problem but I don't know for sure.
Heres my code
<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];
if(!isset($firstname) || !isset($lastname) || !isset($username) || !isset($password) || !isset($passwordconf) || !isset($email) || !isset($securityq) || !isset($qanswer))
{
echo "You did not fill out the required fields.";
}
$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0)
{
echo "The username you entered is already taken";
}
$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
{
echo "The email you entered is already registered";
}
if($password != $passwordconf)
{
echo "The passwords you entered do not match";
}
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}
else
{
$salt = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
$hpassword = crypt($password,$salt);
$insert = "INSERT INTO users (firstname, lastname, username, password, email, securityq, qanswer, salt)
VALUES ('$firstname','$lastname','$username','$hpassword','$email','$securityq','$qanswer','$salt')";
mysql_query($insert);
if(!mysql_query($insert))
{
die('Could not submit');
}
else
{
echo "Information was submited. Please check your email for confirmation";
}
}
?>
Let me try to answer.
First of all, I agree with advice to move to PDO. mysql_* functions are deprecated. But if you wish to use it, escape every variable directly before sql due to '-symbols in your sql:
$hpassword = mysql_real_escape_string($hpassword );
As for me, the following syntax is easier to view rather than insert ... values():
$insert = "INSERT INTO `users`
SET `firstname` = '$firstname',
SET `hpassword` = '$hpassword'..."
Actually, I am trying to forgot this kind of code. I use PDO or comfortable uniDB class for simple apps.
Is it correct behaviour that it inserts user no matter errors like matching password? You should fix conditions.
Your conditions logic is wrong. You submit after if(!preg_match($regex, $email)). So if email is correct, it submits. Fix it as follows using ELSEIF
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(mysql_num_rows($emailquery) > 0){
echo "The email you entered is already registered";
}elseif($password != $passwordconf){
echo "The passwords you entered do not match";
}elseif(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}else{
// insertion code HERE
}

trying insert a checkbox in a form of terms and condition

I am trying to input a check-box for terms and conditions in a form, but when I registered the form without ticking the box the registration went through , (which was not suppose to be). Please help have a look.
<?php
echo "<h2>Register</h2>";
$submit = $_POST['register'];
//form data
$fullname = mysql_real_escape_string(htmlentities(strip_tags($_POST['fullname'])));
$username = strtolower(mysql_real_escape_string(htmlentities(strip_tags($_POST['username']))));
$password = mysql_real_escape_string(htmlentities(strip_tags($_POST['password'])));
$repeatpassword = mysql_real_escape_string(htmlentities(strip_tags($_POST['repeatpassword'])));
$email = mysql_real_escape_string(htmlentities(strip_tags($_POST['email'])));
$houseno = mysql_real_escape_string(htmlentities(strip_tags($_POST['houseno'])));
$addressa = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressa'])));
$addressb = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressb'])));
$addressc = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressc'])));
$county = mysql_real_escape_string(htmlentities(strip_tags($_POST['county'])));
$state = mysql_real_escape_string(htmlentities(strip_tags($_POST['state'])));
$country = mysql_real_escape_string(htmlentities(strip_tags($_POST['country'])));
$accept = mysql_real_escape_string(htmlentities(strip_tags($_POST['accept'])));
if ($submit)
{
$namecheck = mysql_query("SELECT username FROM reusers WHERE username='$username'");
$count = mysql_num_rows($namecheck);
if($count!=0)
{
die("Username already taken!");
}
//check for registration form details
if ($fullname&&$username&&$password&&$repeatpassword&&$email&&$houseno&&$addressa&&$county&&$state&&$country)
{
if($accept!= 1)
{
if ($password==$repeatpassword)
{
//check char lenght of username and fullname
if (strlen($username)>25||strlen($fullname)>25)
{
echo "Lenght of username or fullname is too long";
}
else
{
//check password length
if(strlen($password)>25||strlen($password)<6)
{
echo"Password must be between 6 and 25 characters";
}
else
{
//check password length
$emailcheck = mysql_query("SELECT email FROM reusers WHERE email='$email'");
$ecount = mysql_num_rows($emailcheck);
if($ecount!=0)
{
echo"email already registered Please sign in into your account to continue";
}
else
{
//generate random code
$code = rand(11111111,99999999);
//send activation email
$to = $email;
$subject = "Activate your account";
$headers = "From: donotreply#reacheasy.co.uk";
$body = " Hello $fullname,\n\nUsername $username,\n\n Password $password ,\n\nYou registered `and need to activate your account. Click the link below or paste it into the URL bar of your browser\n\nhttp://reach.co.uk/activate.php?code=$code\n\nThanks!";
if (!mail($to,$subject,$body,$headers))
echo "We couldn't sign you up at this time. Please try again later.";
else
{
//register the user!
//encript password
$password = md5($password);
$repeatpassword = md5($repeatpassword);
$queryreg = mysql_query("
INSERT INTO reusers VALUES ('','$fullname','$username','$password','$email','$code','0','houseno','addressa','addressb','addressc','county','state','country')
");
die("You have been registered successfully! Please check your email ($email) to activate your account<a href='index.php'>Return to login page</a>");
}
}
}
}
}
else
echo"Your passwords do not match!";
}
else
echo"Please read and accept Terms and Conditions before registering!";
}
else
echo "Please fill in <b>all</> fields!";
}
?>
$accept = ($_POST['accept'] ? 1:0);
You must use
if($accept == 1)
because $_POST['accept'] = 1 when you check the checkbox.
Now return Please read and accept Terms and Conditions before registering! when checkbox is checked and register the user when checkbox is not checked.

Categories