PHP form only submits data for one row - php

I am working on a simple registration system and after hours of research am still stuck.
If my database is clear (I delete any rows in the table), and I submit the form, it sends a validation email and activates and allows me to login.
If I try to create another account with the same email, I am not getting my error message like I should be, telling the user "the email has already been registered." It just takes me to a blank page, even if I use a new email address after the first row has been created.
When I look at my table, the row created by the form (the first time) has the auto-inc ID which is right, the username is input into the row, but password, email, and activation all say '0'.
Can anyone see where the error is in my code? I need the code to verify that the email entered isn't already used, and if it is, to display the errormessage. If it isn't, it should be creating a new row in the table with the information.
I know I need to hash the password. I'm just trying to get the information in the table right before I proceed with security.
index.php
<?php
include 'sessions.php';
if(isset($_SESSION['errormessage'])){
echo ($_SESSION['errormessage']);
unset ($_SESSION['errormessage']);
}
?>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<form name="newForm" method="post" action="createaccount.php">UserName:
<input type="text" name="newUserName" size="15" maxlength="15">
<br>Password:
<input type="password" name="newPass1" size="15">
<br>Confirm Password:
<input type="password" name="newPass2" size="15">
<br>Email:
<input type="email" name="newEmail" size="15">
<br>
<input type="submit" name="newSubmit">
<input type="reset" name="newReset">
</p>
</form>
<hr>
<form name="newForm" method="post" action="login.php">
<strong>Already Registered? Login Here:</strong>
<br>
UserName:
<input type="text" name="UserName" size="15" maxlength="15">
<br>Password:
<input type="password" name="Pass1" size="15">
<br>
<input type=submit name=SubmitButton value=Submit>
<input type=reset name=ResetButton value=Clear>
</form>
</body>
</html>
createaccount.php
<?php
include ('sessions.php');
include ('database_connection.php');
//function to test password
function passwordStrength($pwd) {
//test for at least 8 characters
if (strlen($pwd) < 8) {
return false;
}
//test for max length
if (strlen($pwd) > 16) {
return false;
}
//test to see if password contains number
if(!preg_match("#[0-9]+#", $pwd)) {
return false;
}
//test to see if password has capital letter
if(!preg_match("#[A-Z]+#", $pwd)) {
return false;
}
//test to see if password has a lowercase letter
if(!preg_match("#[a-z]+#", $pwd)) {
return false;
}
//test to see if password has special character
if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
return false;
}
//test to see if password contains a space
if (strpos($pwd, ' ') > 0) {
return false;
}
else {
return true;
}
return true;
}
if(isset($_POST['newSubmit'])){
if(empty($_POST['newUserName'])) {
$_SESSION['errormessage'] = "Please enter a username!";
header("Location: index.php");
}
else if (strlen($_POST['newUserName']) < 4) {
$_SESSION['errormessage'] = "Username is too short!";
header("Location: index.php");
} else if(strlen($_POST['newUserName']) > 16) {
$_SESSION['errormessage'] = "Username is too long!";
header("Location: index.php");
} else if(empty($_POST['newPass1'])) {
$_SESSION['errormessage'] = "You must enter a password!";
header("Location: index.php");
} else if(empty($_POST['newPass2'])) {
$_SESSION['errormessage'] = "You must confirm your password!";
header("Location: index.php");
} else if($_POST['newPass1'] !== $_POST['newPass2']) {
$_SESSION['errormessage'] = "Passwords do not match!";
header("Location: index.php");
} else if(!passwordStrength($_POST['newPass1'])) {
$_SESSION['errormessage'] = "Password does not meet requirements!";
header("Location: index.php");
} else if(empty($_POST['newEmail'])) {
$_SESSION['errormessage'] = "Must enter an email address!";
header("Location: index.php");
} else {
$Email = $_POST['newEmail'];
$name = $_POST['newUserName'];
$Password = $_POST['newPass1'];
//echo "All fields accepted!";
//$pwd = $_POST['newPass1'];
//echo hash("sha256", $pwd);
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
$result_verify_email = mysqli_query($db, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
$_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
header("Location: index.php");
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO `userDB` ( `username`, `email`, `password`, `activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($db, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($db) == 1) { //If the Insert Query was successfull.
//send the email
$to = $_POST['newEmail']; // this is your Email address
$from = "mtshort87#gmail.com"; // this is the sender's Email address
$subject = "Account Succesfully Created";
$message = "Thank you for creating an account. Please activate it now using the link below!";
$message2 = "http://cts.gruv.org/short/form/activate.php?username=".$_POST['newUserName']."\n";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message2,$message,$headers);
mail($from,$subject,$message2,$message,$headers); // sends a copy of the message to the sender
$_SESSION['errormessage'] = "A confirmation e-mail has been sent to you. Please activate your account to login.";
header("Location: index.php");
}
mysqli_close($db);//Close the DB Connection
}
}
}
activate.php
<?php
include 'sessions.php';
include 'database_connection.php';
if (isset($_GET['Email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $_GET['Email']))
{
$email = $_GET['Email'];
}
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))//The Activation key will always be 32 since it is MD5 Hash
{
$key = $_GET['key'];
}
if (isset($Email) && isset($key))
{
// Update the database to set the "activation" field to null
$query_activate_account = "UPDATE userDB SET activation=NULL WHERE(email ='$Email' AND activation='$key')LIMIT 1";
$result_activate_account = mysqli_query($db, $query_activate_account) ;
// Print a customized message:
if (mysqli_affected_rows($db) == 1)//if update query was successfull
{
echo '<div class="success">Your account is now active. You may now Log in</div>';
} else
{
echo '<div class="errormsgbox">Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';
}
mysqli_close($db);
} else {
echo '<div class="errormsgbox">Error Occured .</div>';
}
?>
If any more information is requested I will edit this post.

$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
$result_verify_email = mysqli_query($db, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
$_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
header("Location: index.php");
}
http://php.net/manual/en/mysqli.query.php
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
Since you are using a correct SQL select statement, mysqli_query will return a mysqli_result object.
There is a num_rows attribute in mysqli_result that indicates the number of rows found. You can use it to check if there is a record with that email.
Always use LIMIT 1 when you expect 1 result.
FIX:
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email' LIMIT 1";
$result_verify_email = mysqli_query($mysqli, $query_verify_email);
if (is_object($result_verify_email) && $result_verify_email->num_rows > 0) {
echo "Email already exists";
}

Related

Secure two way hashing technique [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am currently developing a Document Authentication System and I want the Passwords of the users to be hashed or encrypted ..
So my question is, what is the best and most secure TWO WAY Hashing or Encrypting method I will use ..
As it has been suggested in the comments above the best and easy way is to use password_hash(); and password_verify(); more info is available in the php.net website, and also make use of prepared statements either with mysqli or pdo in my basic user registration i made use of PDO.
Please not this is just a basic example of how to use password_hash and password_verify();
we will use the password_hash() upon registration and password_verify() upon login
db.php
<?php
$server="localhost";
$username="root";
$password="";
try{
$dbh = new PDO("mysql:host=$server;dbname=sytemDb",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $exc){
error_log($exc);
}
?>
The above script makes connection to our database.
register.php
<?php
include 'db.php';
$errors="";
if (isset($_POST['register'])) {
//check if values are not empty
if(empty($_POST['email'])){
die("please enter email");
$errors++;
}else{
$email = $_POST['email'];
//then check for valid email
}
}
if(empty($_POST['upass'])){
die("enter password");
$errors++;
}else{
$password = $_POST['upass'];
$hash = password_hash($password,PASSWORD_DEFAULT);//hashing password
}
if($errors <=0){
//no errors save to db
$stmt= $dbh->prepare("INSERT INTO users (username,password) VALUES(?,?)");
$stmt->execute(array($username,$hash));
echo "User registered";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="email" name="email" placeholder="Ente Username">
<input type="password" name="upass" placeholder="Enter Password">
<button type="submit" name="register">Register</button>
</form>
</body>
</html>
Login.php
<?php
ob_start();
session_start();
include 'db.php';
if(isset($_POST['login'])){
if(empty($_POST['username']) || empty($_POST['pass'])){
die("enter password or username");
}else{
$uname = $_POST['username'];
$password = $_POST['pass'];
}
try {
$stmt = $dbh->prepare("SELECT userid,password,username from users where username = ?");
$stmt->bindValue(1,$uname);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
//if username is correct continue check entered password against saved hash
foreach ($results as $row) {
if(password_verify($password,$row['password'])){
//password and saved hash match go to dashboard
echo "login success";
$_SESSION['user']= $row['userid'];
header("refresh:5;url=dashboard");
}else{
echo "username and password does not match";
}
}
}else{
echo "username and password does not match";
}
} catch (PDOException $e) {
error_log($e);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="POST" action="">
<input type="text" name="username" placeholder="Enter username">
<input type="password" name="pass" placeholder="Enter password">
<button type="submit" name="login">Login</button>
</form>
</body>
</html>
This should do its very basic password hash is available in the manual here and here
password_verify() also available here
Please make use of php 5.6 or above of which u were supposed to already do.
That's about it. Hope this will point you to the correct direction.
NB: Always verify input from the user, don't forget to filter and
sanitize the input then prepare a statement to save to the db.
incase a user forget a password, well there are many ways to reset the user password, one basic way is to have an autho token column on ur db.
The following way is very basic for beginners just to kickoff your career lol ;)
<?php
function ForgetPassword()
{
try {
//search the user on the database
$stmt = $dbh->prepare("SELECT email,userid,firstname,lastname from users where email = ?");
$stmt->bindvalue($email);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) { //user found generate authentication token
foreach ($results as $row):
$userid = base64_encode($row['userID']);
$randomAuth = md5(uniqid(rand()));
$dataUpdate = $dbh->prepare("UPDATE users set auth_token = ? where email = ?");
$dataUpdate->execute(array(
$randomAuth,
$row['email']
));
//send reset link to the user
$link = "Reset your password";
$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$header .= 'From: <>' . "\r\n";
$message = "<p> Hello " . $row['firstname'] . " " . $row['lastname'] . "</p>";
$message .= "<p> You have requested to reset your password your password</p>";
$message .= "<p>" . $link . "</p>";
if (mail(($row['email']), "Password Reset", $message, $header)) {
$successMessage = "Reset link sent to the provided email address";
} else {
error_log("cound not send message");
}
endforeach;
} else {
$successMessage = "Reset link sent to the provided email address";
}
}
catch (PDOException $ex) {
error_log($ex);
}
}
?>
Then reset passwordpage
<?php
function resetPassword()
{
if (isset($_GET['code']) && isset($_GET['token'])) {
$code = base64_decode($_GET['code']);
$token = $_GET['token'];
if (isset($_POST['resetpassword'])) {
//check empty fields
if (empty($_POST['newpassword'])) {
$errorMessage = "enter password";
$errors++;
return $errorMessage;
} else {
$password = $_POST['newpassword'];
$hash = password_hash($password, PASSWORD_DEFAULT); //password encryption
}
if (!empty($_POST['newpassword']) && empty($_POST['confirmpassword'])) {
$errorMessage = "Please confirm your password";
$errors++;
return $errorMessage();
}
if (!empty($_POST['confirmpassword']) && $_POST['confirmpassword'] !== $_POST['newpassword']) {
return "Passwords does not match";
$errors++;
}
}
if ($errors <= 0) {
try {
$stmt = $dbh->prepare("Update users set password = ? where userID = ? AND auth_token = ?");
$stmt->execute(array(
$hash,
$code,
$token
));
return "Password successfully changed.. Redirecting to login page";
$update = $dbh->prepare("UPDATE users set aut_token = NULL where userID = ? ");
$update->bindValue(1, $code);
$update->execute();
header("refresh=3:url;login");
}
catch (PDOException $e) {
error_log($e->getMessage());
}
}
} else {
//token code error
return "The link have expired, please go back and request a new one";
}
}
?>

php check and validate form input with mysql database [duplicate]

This question already has an answer here:
PHP's white screen of death [duplicate]
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
Basically I have this form that asks for email and password.
What I want to do is to compare and check if the inputs match with the data from my table/database.
This is my registration.php (the form)
<form action="Authentication.php" method="post">
<b>Returning Intern Login</b><br/><br/>
Enter your e-mail address: <input type="text" name="email" /><br/><br/>
Enter your password: <input type="password" name="pw2"/><br/><i>(Passwords are case-sensitive and must be 6 characters long)</i><br/><br/>
<input type="reset" value="Reset Login Form" />
<input type="submit" name="submit2" value="Log In" /><hr/><br/>
</form>
and this is the Authentication.php
session_start();
$link = mysqli_connect('localhost','root','');
$database = mysqli_select_db($link,'internship');
$user = $_POST['email'];
$pass = $_POST['pw2'];
// User is logging in
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
It works with the empty inputs.
But when I gave an email and password exactly same from the database/table,
It displays white blank page..
You need to write the entire code within an if statement to ensure the field is filled in, like so:
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
/* Code */
}
if (empty ($pass)) //if password field is empty echo below statement
{
/* Code */
}
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
else
{
echo "Empty input submit2"; // empty $_POST["submit2"]
}
Hope this helps.
Mysqli takes 4 parameters hostname,username,password, and dbname:
<?php
session_start();
$link = mysqli_connect('localhost','root','','internship');
// User is logging in
if (isset($_POST["submit2"]))
{
$user = $_POST['email'];
$pass = $_POST['pw2'];
if (empty($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
else if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". $user ."' AND password = '".$pass."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
?>

PHP registration form to send email to multiple recipients

I know that similar questions to mine have been asked here. I have searched but they are not very relevant to my problem and the solution I am seeking for.
I have this PHP script that I am using for member registration on my website. It is meant to only send a confirmation/verification email to the registrant, but I want it to also send a notification email to me, the admin, that someone has registered with their information. I don't know how to go about achieving this.
Here is the code:
<?php
include 'dbc.php';
$err = array();
if($_POST['doRegister'] == 'Register')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value);
}
require_once('recaptchalib.php');
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die ("<h3>Image Verification failed!. Go back and try again.</h3>" .
"(reCAPTCHA said: " . $resp->error . ")");
}
if(empty($data['first_name']) || strlen($data['first_name']) < 4)
{
$err[] = "ERROR - Please enter your first name";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['last_name']) || strlen($data['last_name']) < 4)
{
$err[] = "ERROR - Please enter your last name";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['tel']) || strlen($data['tel']) < 6)
{
$err[] = "ERROR - Please enter your phone number";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['address']) || strlen($data['address']) < 6)
{
$err[] = "ERROR - Please enter your contact address";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['city']) || strlen($data['city']) < 3)
{
$err[] = "ERROR - Please enter your city of residence";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['state']) || strlen($data['state']) < 3)
{
$err[] = "ERROR - Please enter your state of residence";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['country']) || strlen($data['country']) < 3)
{
$err[] = "ERROR - Please choose your country of residence";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['birth_date']) || strlen($data['birth_date']) > 10)
{
$err[] = "ERROR - Please choose your date of birth";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['gender']) || strlen($data['gender']) < 4)
{
$err[] = "ERROR - Please enter your gender";
//header("Location: register.php?msg=$err");
//exit();
}
if(empty($data['description']) || strlen($data['description']) < 10)
{
$err[] = "ERROR - Please describe yourself";
//header("Location: register.php?msg=$err");
//exit();
}
// Validate User Name
if (!isUserID($data['user_name'])) {
$err[] = "ERROR - Invalid user name. It can contain alphabet, number and underscore.";
//header("Location: register.php?msg=$err");
//exit();
}
// Validate Email
if(!isEmail($data['usr_email'])) {
$err[] = "ERROR - Invalid email address.";
//header("Location: register.php?msg=$err");
//exit();
}
// Check User Passwords
if (!checkPwd($data['pwd'],$data['pwd2'])) {
$err[] = "ERROR - Invalid Password or mismatch. Enter 6 chars or more";
//header("Location: register.php?msg=$err");
//exit();
}
$user_ip = $_SERVER['REMOTE_ADDR'];
// stores sha1 of password
$sha1pass = PwdHash($data['pwd']);
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
// Generates activation code simple 4 digit number
$activ_code = rand(1000,9999);
$usr_email = $data['usr_email'];
$user_name = $data['user_name'];
/************ USER EMAIL CHECK ************************************
This code does a second check on the server side if the email already exists. It
queries the database and if it has any existing email it throws user email already exists
*******************************************************************/
$rs_duplicate = mysql_query("select count(*) as total from users where user_email='$usr_email' OR user_name='$user_name'") or die(mysql_error());
list($total) = mysql_fetch_row($rs_duplicate);
if ($total > 0)
{
$err[] = "ERROR - The username/email already exists. Please try again with different username and email.";
//header("Location: register.php?msg=$err");
//exit();
}
/***************************************************************************/
if(empty($err)) {
$sql_insert = "INSERT into `users`
(`first_name`,`last_name`,`user_email`,`pwd`,`tel`,`address`,`city`,`state`,`birth_date`,`gender`,`description`,`date`,`users_ip`,`activation_code`,`country`,`user_name`
)
VALUES
('$data[first_name]','$data[last_name]','$usr_email','$sha1pass','$data[tel]','$data[address]','$data[city]','$data[state]','$data[birth_date]','$data[gender]','$data[description]'
,now(),'$user_ip','$activ_code','$data[country]','$user_name'
)
";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
$user_id = mysql_insert_id($link);
$md5_id = md5($user_id);
mysql_query("update users set md5_id='$md5_id' where id='$user_id'");
// echo "<h3>Thank You</h3> We received your submission.";
if($user_registration) {
$a_link = "
*****ACTIVATION LINK*****\n
http://$host$path/activate.php?user=$md5_id&activ_code=$activ_code
";
} else {
$a_link =
"Your account is *PENDING APPROVAL* and will be soon activated by the administrator.
";
}
$message =
"Hello $data[first_name] $data[last_name], \n
Thank you for your interest in Kisil Entertainment Network. Either you or someone representing you submitted your registration details on our website; http://$host$path. If you neither submitted nor authorized anyone to submit on your behalf, please kindly ignore and immediately delete this message. If you either submitted or authorized someone to submit on your behelf, click on the link below to activate your account and complete your registeration with Kisil Entertainment Network. Here are your login details...\n
User ID: $user_name
Email: $usr_email \n
Passwd: $data[pwd] \n
Click on this link to activate your account $a_link.
If you cannot click on the link, go to http://$host$path/activate.php and paste this activation code: $activ_code into the activation box.
You are welcome to the Kisil Entertainment Network family.
Kind regards,
Kisil Entertainment Network
http://$host$path
Nigeria's No.1 Entertainment Network. /n
______________________________________________________
NOTE: THIS IS AN AUTOMATICALLY GENERATED RESPONSE.
***DO NOT REPLY TO THIS EMAIL****
";
send_mail( 'Kisil Entertainment Network.<noreply#kisilentertainmentnetwork.com>',
$usr_email,
'Activate your account',
$message);
header("Location: thankyou.php");
exit();
}
}
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$user_email = $data['usr_email'];
$pass = $data['pwd'];
if (strpos($user_email,'#') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";
}
$result = mysql_query("SELECT `id`,`pwd`,`first_name`,`last_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$first_name,$last_name,$approved,$user_level) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $first_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
Just add your mail id in BCC of php mail script. Then you receive mail for user registration.

Login form validation and error message in PHP

I have a login form that requires a username and a password. I want the top of the form to say "Invalid Password" or "Invalid Username" if the login credentials are wrong. Could someone please offer insight into doing this?
The message says "Invalid Password" if one field is empty right now. I want it to have messages even if there is something in the field if it is wrong.
Here is the Login Form:
<form action="index.php?action=login" method="post">
<fieldset>
<div style="color:red;"><?php echo isset($_REQUEST['err']) && $_REQUEST['err'] == 1 ? "Invalid Password" : "";?></div>
<legend>Login</legend>
<label for="loginName" class="required">Username:</label>
<input id="loginName" name="loginName" type="text"
value="" required />
<label for="password" class="required">Password:</label>
<input id="password" name="password" type="password"
value="" required />
<input id="submit" class="submit" type="submit" value="login"/>
</fieldset>
</form>
This is the login function (it is for a member/admin website so logs into two accounts):
function connect($loginName) {
global $db;
$query = "SELECT email, level, password FROM members WHERE email = '$loginName'";
$result = $db->query($query);
$results = $result->fetch(PDO::FETCH_ASSOC);
return $results;
}
//Login
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/admin/home.php?err=1');
}
if ($loginName === $results['email'] && password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
}
header('Location: /tire/admin/home.php');
}
//Logout
function logout() {
$_SESSION = array();
session_destroy();
}
#bakriawad Here it is where I'm trying your suggestion and it still isn't working. It's telling me $loginName and $password are undefined indexes.
function error_message(){ unset($error);
$loginName = $_SESSION['loginName'];
{$results = connect($loginName);
$loginName === $results['email'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$passwords = password_verify($password,$results['password']);
if(!$results) {$error = "Username not found";} //if no records returned, set error to no username
else //if found {
if ((isset($password)) !== (isset($passwords))) //check password, if matched log him in
{ $error = "Password is wrong"; } //if not matched then set error message
}
}
if(isset($error))echo $error; //if there is an error print it, this can be anywhere in the page
}
PHP side:
(peusedo code)
{
unset($error); // or $error="";, just reset it
$loging = select from database where username = 'username'; //get data from database
if(!$loging) {$error = "Username not found";} //if no records returned, set error to no username
else //if found
{
if ($password == $loging['pass']) {login();} //check password, if matched log him in
else $error = "Password is wrong"; //if not matched then set error message
}
if(isset($error))echo $error; //if there is an error print it, this can be anywhere in the page
}
Java script side:
make an ajax call to php function that checks login sending username and password, if it is correct redirect the page to welcome screen, if not change the style of box and / or display error message
you will have to research this as i never used ajax
try to do it your self, if you stumble i will be happy to provide you with a sample

change password in mysql table?

Hi im having a problem with my change password script. im trying to allow a user to change their password in the mysql table 'ptb_users.password' it's suppose to store this as md5.
When i hit submit in my form, i'm assuming it goes to changepassword.php but the page is just blank, nothing is echoed and im not getting any errors.
Can someone please show me where im going wrong with this, thanks
Here's my form:
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php");
require('includes/checks.php');
?>
<?php
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form method="post" action="includes/changepassword.php" name="form1" id="form1">
<input type="password" name="oldpassword" id="password" class="subject" placeholder="Old Password">
<input type="password" name="oldpassword" id="password" class="message" placeholder="Old Password">
<input type="password" name="newpassword" id="newpassword" class="message" placeholder="New Password">
<input type="image" src="assets/img/icons/loginarrow1.png" name="submit" id="submit" class="submit">
</form>
And here's my mysql function:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
?>
<?php
session_start();
include '_config/connection.php';
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']."");
if(!$result)
{
echo "The username you entered does not exist";
}
else
if($password!= mysql_result($result, 0))
{
echo "";
}
if($newpassword=$confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm new password fields must be the same";
}
?>
if(isset($_POST['submit']))
{
$email = $_POST['email'];
echo $newpassword = ($_POST['password1']);
echo $confirmpasssword = ($_POST['password2']);
if($newpassword=$confirmpassword)
{
echo $newpassword = md5($newpassword);
echo $result = mysql_query("UPDATE users SET password='$newpassword' WHERE email='$email' ");
}
if($result)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm password fields must be the same";
}
}
can anyone tell me is this correct coding, to change password and store in mysqldb.
first you do not check the old password properly (md5 stored, plaintext compare... won't work)
second you do not have any confirmpassword set, so this wont work too
what would work is:
$password = md5($_POST['password']);
$newpassword = md5($_POST['newpassword']);
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']." AND password = '".$password."'");
if(!$result)
{
echo "The username you entered does not exist or old password didn't match";
}
else
{
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
There are many things wrong with this.
Let's get the basics out of the way first:
Don't use mysql_ functions. switch to PDO or mysqli while you can.
md5 is in its dying days. See this answer - understandably, you may be so entrenched in md5 you can't get out without pestering every user to update their pw.
Your problem then is this:
if($password!= mysql_result($result, 0))
You're not comparing against a md5 stored hash. It should be something like this:
if(md5($password) != mysql_result($result, 0))
and this:
if($newpassword=$confirmnewpassword)
is just reassigning a variable. I think you wanted
if($newpassword == $confirmnewpassword)
As for output, you may want to consider the if/else structures you're using here. This could be cleaned up significantly and all together looks out of date. Maybe just an opinion.
If you have a specific thing to hone in on, let me know and I may update.
EDIT
This whole block should be cleaned. Something like this may help:
if(!$result)
{
echo "The username you entered does not exist";
}
else
{
if(md5($password) != mysql_result($result, 0))
{
echo "Current PW does not match what we have";
}
else
{
if($newpassword == $confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."") or die(mysql_error());
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
}
else
{
echo "The new password and confirm new password fields must be the same";
}
}
}

Categories