Here is the register.inc.php
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
include_once 'functions.php';
$error_msg = "";
sec_session_start();
if (isset($_POST['username'], $_POST['email'], $_POST['p'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['contactno'], $_POST['address'], $_POST['inviteid']
)) {
// Sanitize and validate the data passed in
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$phone = filter_input(INPUT_POST,'contactno', FILTER_SANITIZE_STRING);
$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
$lastname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING);
$inviteid = filter_input(INPUT_POST, 'inviteid', FILTER_SANITIZE_STRING);
$address = filter_input(INPUT_POST, 'address', FILTER_SANITIZE_STRING);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Invalid password configuration.</p>';
}
// Username validity and password validity have been checked client side.
// This should should be adequate as nobody gains any advantage from
// breaking these rules.
//
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
// check existing email
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error" style="color:red; font-size:16px;">* A user with this email address already exists.</p>';
$stmt->close();
}
} else {
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error Line 39</p>';
$stmt->close();
}
// check existing username
$prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this username already exists
$error_msg .= '<p class="error" style="color:red; font-size:16px;">* A user with this username already exists</p>';
$stmt->close();
}
} else {
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error line 55</p>';
$stmt->close();
}
// check existing username
$prep_stmt = "SELECT id FROM members WHERE myid = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s',$_POST['inviteid']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
// A user with this us
$error_msg .= '<p class="error" style="color:red; font-size:16px;">* No user with this id exists</p>';
$stmt->close();
}
} else {
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error line 55</p>';
$stmt->close();
}
//1.86€y9.31€$Ac2w6xufmG.jI3F/5GZhDOdW1TzAPrnJ3oPF0seGHI6g03QopB4C
// TODO:
// We'll also have to account for the situation where the user doesn't have
// rights to do registration, by checking what type of user is attempting to
// perform the operation.
if (empty($error_msg)) {
// Create hashed password using the password_hash function.
// This function salts it with a random salt and can be verified with
// the password_verify function.
$passwords = password_hash($password,PASSWORD_BCRYPT);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password,firstname,lastname,phone,address,inviteid) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssssssss', $username, $email, $passwords, $firstname, $lastname, $phone, $address, $inviteid);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
/*if (login($_POST['email'],$_POST['p'], $mysqli) == true) {
// Login success
header('Location: dashboard.php');
}else{
// Login failed
//header('Location: login.php');
} */
// header('Location: dashboard.php');
//exit();
}
}
?>
process_login.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
include_once '../securimage/securimage.php';
//$securimage = new Securimage();
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
// header("Location: ../protected_page.php");
header('Location: ../dashboard.php');
}else{
// Login failed
header('Location: ../login.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
header('Location: ../error.php?err=Could not process login');
exit();
}
Hi there I am trying to hash my passwords with password_hash() in PHP. This part is fine but to compare the hash is returning false no matter what. To log in I check the user account database and grab the password hash then compare it to the password typed in.Have checked all solutions here.
My code looks like this:
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, myid, firstname, lastname,status,ambLevel
FROM members
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $myid, $fname, $lname, $status,
$ambLevel);
$stmt->fetch();
var_dump($db_password);
var_dump($password);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted. We are using
// the password_verify function to avoid timing attacks.
if (password_verify($password,$db_password)) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $fname;
$_SESSION['lastname'] = $lname;
$_SESSION['myid'] = $myid;
$_SESSION['email'] = $email;
$_SESSION['status'] = $status;
$_SESSION['ambLevel'] = $ambLevel;
$_SESSION['login_string'] = hash('sha512',
$db_password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
Please kindly help. View my full source code here.
Works as expected...
<?php
$hash=password_hash("password", PASSWORD_DEFAULT);
if (password_verify("password", $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
I've had the same issue, and resolved it by setting the password column in my DB to a sufficiently long (255) VARCHAR instead of CHAR or NCHAR variable. If this doesn't help, try var_dump at all the transfer points: when first hashing, taking it from the database itself, and after submitting your query.
I have a password reset script that has email and password validation. How can I make the script redirect the user to the same URL (ie. "https://www.domain.com/resetpassword.php?token=...") if they fail to meet the validation? Currently, if the validation test fails, the user is redirected to the URL: https://www.domain.com/resetpassword.php. The token is now gone and the password reset page becomes useless.
Here is my PHP code:
<?php
ob_start();
session_start();
include 'connect.php';
// Was the form submitted?
if (isset($_POST['btn-reset']))
{
// Gather the post data
$email = trim($_POST['email']);
$email = strip_tags($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$cpass = trim($_POST['cpass']);
$cpass = strip_tags($cpass);
//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have at least 6 characters.";
} else if($pass != $cpass) {
$error = true;
$passError = "Passwords do not match.";
}
// if there's no error, continue to process
if( !$error ) {
$token = $_POST ['token'];
// Retrieve token from database
$stmt = $conn->prepare('SELECT token FROM token WHERE userEmail=? and NOW() < expire_date');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$resetKey = $row['token'];
}
// Does the new reset key match the old one?
if ($resetKey == $token && isset($token))
{
if ($pass == $cpass)
{
//hash and secure the password
$password = password_hash($pass, PASSWORD_DEFAULT);
// Update the user's password
$stmt = $conn->prepare('UPDATE user SET userPass = ? WHERE userEmail = ?');
$stmt->bind_param('ss', $password, $email);
$stmt->execute();
$conn = null;
$sucMSG = "Your password has been successfully reset.";
unset($email);
unset($pass);
unset($cpass);
unset($token);
unset($resetKey);
}
else
$matchError = "Your password's do not match.";
}
else
$keyError = "Your password reset key is invalid.";
}
}
?>
And then I have the errors appear in my form using PHP if the values of the errors are set.
Help please with this password change script
here's mys html code
<form method="POST" action="pass.php">
Current Password:
<input type="password" name='password'/>
New Password
<input type="password" id="password1" name="password1"/>
Retype New Password:</td>
<input type="password" id="password2" name="password2"/>
<input type="submit" value="Change Password">
</form>
here's my php script for change password. it's working fine but when i try to login the new password it is always incorrect.
$userData = $qry->fetch(PDO::FETCH_ASSOC);
$hash = hash('sha256',$userData['salt'].hash('sha256',$password));
if ($hash == $userData['password']) {
$hash1 = hash('sha256', $password1);
function createSalt()
{
$text = md5(uniqid(rand(), TRUE));
RETURN substr($text, 0, 3);
}
$salt = createSalt();
$pass = hash('sha256', $salt . $hash1);
$qry = $handler->prepare( "UPDATE login SET password = ? WHERE id = ?" );
$qry->execute(array($pass,$id));
$error = 'Password successfully changed! The system will now log you out. Please login again.';
session_destroy();
header('refresh:5; url=/../lab/login.php');
}else{
$error = 'Incorrect Password.';
}
Here's my login script for reference.
<?php
$errors = array();
if ($email&&$pass){
$qry = $handler->prepare( "SELECT `email` FROM login WHERE `email` = ?" );
$qry->bindValue( 1, $email );
$qry->execute();
$row = $qry->rowCount();
if ($row == 1){
$qry = $handler->prepare( "SELECT * FROM login WHERE email = ? AND stat = '1'" );
$qry->bindValue( 1, $email );
$qry->execute();
$row = $qry->rowCount();
if ($row == '1'){
$userData = $qry->fetch(PDO::FETCH_ASSOC);
$hash = hash('sha256',$userData['salt'].hash('sha256',$pass));
if($hash == $userData['password']){
$_SESSION['email']=$email;
header('Location:/../lab/profile.php');
}
else{
$errors = "<center>The Password/Email you Entered is incorrect. Please check your login Details and <br><a href='/../lab/login.php' style='font-size:12px;text-decoration:underline;'>Login Again</a></center> ";
}
}
else{
$errors = "Your Account is not yet activated. Please check your email.";
}
}
else{
$errors = "<center>The Password/Email you Entered is incorrect. Please check your login Details and <br><a href='/../lab/login.php' style='font-size:12px;text-decoration:underline;'>Login Again</a></center>";
}
}
else{
$errors = "Please fill in the Email and Password fields to login";
}
?>
Everything is working. It's just when I try to change password and then login the new password, the system returns incorrect password. maybe there's some problem with encrypting the new password.
Thanks
Is that the full php script?
There are many ways to debug this.
Try to echo $_POST['password1']; maybe it doesn't have a value.
did you try $hash1 = hash('sha256', $_POST['password1']);?
or maybe you forgot to hash the $pass in if ($email&&$pass)
From what I saw on your code. Listed above is the most critical reason of your problem.
So In my project I'm trying to declare a variable so it will display their full name if logged in. I'm assuming it would be a query to fetch the data from the table but I'm unsure on how to have it make sure it get's that certain user's name and not the first name on the table
Here's my registration code.
if( $user->is_logged_in() ){ header('Location: index.php'); }
//if form has been submitted process it
if(isset($_POST['submit'])){
//very basic validation
if(strlen($_POST['username']) < 3){
$error[] = 'Username is too short.';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $_POST['username']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['username'])){
$error[] = 'Username provided is already in use.';
}
}
if(strlen($_POST['password']) < 3){
$error[] = 'Password is too short.';
}
if(strlen($_POST['passwordConfirm']) < 3){
$error[] = 'Confirm password is too short.';
}
if($_POST['password'] != $_POST['passwordConfirm']){
$error[] = 'Passwords do not match.';
}
//email validation
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//email validation
if(strlen($_POST['fullname']) < 2){
$error[] = 'Please enter a valid full name';
} else {
$stmt = $db->prepare('SELECT fullname FROM members WHERE fullname = :fullname');
$stmt->execute(array(':fullname' => $_POST['fullname']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//if no errors have been created carry on
if(!isset($error)){
//hash the password
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
//create the activasion code
$activasion = md5(uniqid(rand(),true));
try {
//insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (username,password,email,fullname,active) VALUES (:username, :password, :email, :fullname, :active)');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':fullname' => $_POST['fullname'],
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <".SITEEMAIL.">\r\n";
$additionalheaders .= "Reply-To: $".SITEEMAIL."";
mail($to, $subject, $body, $additionalheaders);
//redirect to index page
header('Location: index.php?action=joined');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
Updated with the user class:
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password FROM members WHERE username = :username');
$stmt->execute(array('username' => $username));
$row = $stmt->fetch();
return $row['password'];
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
return true;
}
}
}
Why not simply select them from the database?
Please don't mind me if I mix in a little pseudo code since I'm not very familiar with your variables.
First, you create/start a SESSION if the login credentials are correct.
if($login_credentials_correct){ //lol you know what I mean here
session_start();
$_SESSION['username'] = $_POST['username']; // or wherever it may have come from
}
Now that the session is on, you can perform a query somewhat similar to this
<?php
session_start(); // fixed
$username = $_SESSION['username'];
$stmt = $db->prepare('SELECT fullname FROM members where username= :username');
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$fullName = $row['fullName']; //I am not sure if this is the correct index.
//to make sure, use var_dump($row) and find out which index has the full name
echo $fullName; //voila.
?>
Now, this code only works if your username is unique. Lol. which site has no unique username.
Can you post your log in code? I'll try to answer with what you ave so far.
If you want users to have the ability to log in and have their data available for display do this
if(!($_SERVER['REQUEST_METHOD'] == "POST")){
//Code here for users trying to access page incorrectly
}else{
if(isset($_POST['username']) && ($_POST['username'] <= $UsernameMaxLength)){
$username=strip_tags(stripslashes($_POST['username'])); //Clean the data up
}else{
//Error handling code
}
if(isset($_POST['password']) && ($_POST['password'] <= $PasswordMaxLength)){
//I would advise you use SHA1() instead for password encryption, but I'll use what you used here
$password=$user->password_hash(strip_tags(stripslashes($_POST['password'])), PASSWORD_BCRYPT); //Clean the data up
}else{
//Error handling code
}
if(!isset($username) || !isset($password)){
//Error handling code
}else{
$stmt = $db->prepare('SELECT fullname FROM members where username= :username and password=:password');
$stmt->execute(array('username':$username,'password':$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Code here to make sure there is a row with the number given and all that
//other jazz. In this code I'll assume all went well
if(All_went_well){
//Start your session to store variables you want
session_start();
$_SESSION['fullname']=$row['fullname'];
}
}
}
In your login method, save $username as a session value under $_SESSION['loggedin'] that you can retrieve later like this...
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
return true;
}
}
Then have another method at the bottom of the file that goes something like...
public function get_username(){
if(isset($_SESSION['username'])){
return $_SESSION['username'];
}
}
Then you can call this method like $user->get_username() to get the current logged in users username. Then getting their fullname from the database would require a simple query with "WHERE username = :username". I you can add another method like this to make things easier...
public function get_fullname(){
if(issset($_SESSION['username']){
$stmt = $this->_db->prepare('SELECT fullname FROM members WHERE username = :username');
$stmt->execute(array('username' => $this->get_fullname()));
$row = $stmt->fetch();
return $row['fullname'];
}
}
I'm trying to make a page so users can update their username, email, and password. I have made this script, not sure if it should work or not. When I click update it doesn't make any changes to the account. Not sure what it is. I left the HTML stuff out.
<?php
session_start();
require 'core/init.php';
$uname = $_GET['username'];
$username = $_SESSION['username'];
if(isset($_POST['update'])) {
$uname = $_GET['username'];
if(!empty($_POST['username'])) {
$updateuname = $db->prepare("UPDATE users SET username = :username WHERE username='".$uname."'");
$updateuname->bindValue(':username', $_POST['username'], PDO::PARAM_STR);
$updateuname->execute();
if(!empty($_POST['email'])) {
$updateemail = $db->prepare("UPDATE users SET email = :email WHERE username='".$uname."'");
$updateemail->bindValue(':email', $_POST['email'], PDO::PARAM_STR);
$updateemail->execute();
if(!empty($_POST['password'])) {
if(empty($_POST['password_c'])) {
echo 'You must enter your password in both boxes!';
} else {
if($_POST['password'] == $_POST['password_c']) {
$updatepassword = $db->prepare("UPDATE users SET password = :password WHERE username='".$uname."'");
$updatepassword->bindValue(':password', $_POST['password'], PDO::PARAM_STR);
$updatepassword->execute();
} else {
echo 'Passwords did not match';
}
}
}
}
}
echo 'Details updated!';
}
?>