Why doesn't my password validation work? - php

I'm making a login screen for my blog but when it has to validate the hash it fails. I have googled a lot watched here and asked a few class mates but it still fails. When you submit you get the alert
Wrong password or username!
How can I fix this?
this is my login script
<?php
include_once('resources/db.php');
$sql = "SELECT username, password FROM users WHERE username = :username";
$query = $db->prepare($sql);
$query->execute(array(":username" => $_POST['username']));
$user = $query->fetch(PDO::FETCH_ASSOC);
if ( isset( $_POST['submit'] )) {
$username = $_POST['username'];
$password = $_POST['password'];
$hash_password = $user['password'];
if ( password_verify($password, $hash_password)) {
if ($query->rowCount() == 1){
echo "chrisschotman is ingelogd";
} else {
echo "<script type=\"text/javascript\">alert('Wrong username!')</script>";
}
} else {
echo "<script type=\"text/javascript\">alert('Wrong password or username!')</script>";
}
}
?>
this is my login form
<form action="" method="post">
<input type="text" placeholder="username" name="username"maxlength="24"><br>
<input type="password" placeholder="password" name="password" minlength="8"
maxlength="16"><br>
<input type="submit" value="login" name="submit">
</form>
this is my registration script
<?php
include_once('resources/db.php');
// var_dump($_POST);
$query = $db->prepare('insert into users (`username`, `password`, `privileges`) values(?, ?, ?)');
$query =$db->prepare('select * from users');
$query->execute();
?>
//here is the registration form
<?php
if (isset($_POST)) {
include_once('resources/db.php');
$sql = "INSERT INTO users (`username`, `password`) VALUES (:username, :password)";
$query = $db->prepare($sql);
$query->execute(array(
':username' => $_POST['username'],
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT)
));
if ($query) {
echo "Registered succefully";
} else {
echo "Occured and error";
}
}
?>
database structure
database rows

Change the database row to varchar(255)
$sql = "SELECT username, password FROM users WHERE username = :username";
$query = $db->prepare($sql);
$query->execute(array(":username" => $_POST['username']));
$user = $query->fetch(PDO::FETCH_ASSOC);
And try this registration:
<?php
$db = new PDO('mysql:host=localhost;dbname=' . $db_name . ',' . $db_user . ',' . $db_pass);
if (isset($_POST)) {
include_once('resources/db.php');
$sql = "INSERT INTO users (`username`, `password`) VALUES (:username, :password)";
$query = $db->prepare($sql);
$query->execute(array(
':username' => $_POST['username'],
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT)
));
if ($query) {
echo "Registered succefully";
} else {
echo "Occured and error";
}
}

Related

Sign up process in php being successfully completed when new user doesn't show up in phpmyadmin database

I was following the most popular php tutorial on YouTube on how to create a sign up and log in process using PHP:
https://www.youtube.com/watch?v=LC9GaXkdxF8&t=2216s
I got some issues at first but they were just syntax errors and was able to fix them. When I put in the username, email, password, and retyped password, and clicked sign up, it gave the message that it was successful. The problem was however, when I wen't back to the phpmyadmin database, the new row for the user didn't show up on the table. Now I am thinking this has something to do with phpmyadmin or sql and not the code itself. So the specifics are:
Hosting program: XAMPP
Services turned on: ProFTPD, Apache, MySQL
OS: MacOS
Here are is all the code that I have created by using this tutorial:
signup.inc.php:
<?php
if (isset($_POST['signup-submit'])) {
require 'dbh.inc.php';
$username = $_POST['uid'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
if (empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfields&uid=" . $username . "&mail=" . $email);
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invalidmailuid");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidmail&uid=" . $username);
exit();
}
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invaliduid&uid=" . $email);
exit();
}
else if ($password !== $passwordRepeat) {
header("Location: ../signup.php?error=passwordcheck&uid=" . $username . "&mail=" . $email);
exit();
}
else {
$sql = "SELECT uidUsers FROM users WHERE uidUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror1");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows();
if ($resultCheck > 0) {
header("Location: ../signup.php?error=usertaken&mail=" . $email);
exit();
}
else {
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror2");
exit();
}
else {
$hashedPwd = password_hash($password, PASSSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../signup.php");
exit();
}
?>
dbh.inc.php:
<?php
$servername = 'localhost';
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
signup.php:
<?php
$title = 'Sign Up';
$content = '
<main>
<div id="log-in-box">
<h2>Sign Up and Create an Account</h2>
<form class="form-signup" action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username">
<input type="text" name="mail" placeholder="E-Mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd-repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Sign Up</button>
</form>
</div>
</main>
';
include("template.php");
?>
The MYSQL code he typed into phpmyadmin while setting the database up (and also instead of being called loginsystemtut for the database name I called it loginsystem):
CREATE TABLE users (
idUsers int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
uidUsers TINYTEXT NOT NULL,
emailUsers TINYTEXT NOT NULL,
pwdUsers LONGTEXT NOT NULL
);
and the weird thing is is that I also get this snipet of code showing up while I am in the users table in the database:
SELECT * FROM `users`
The problem has actually been solved. I asked the same question on the r/php subreddit and someone gave me the answer that the guy's code in the video was terrible and told me what to do to fix it. I changed the :
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows();
if ($resultCheck > 0) {
header("Location: ../signup.php?error=usertaken&mail=" . $email);
exit();
}
else {
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror2");
exit();
}
else {
$hashedPwd = password_hash($password, PASSSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
}
to just:
else {
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
$stmt->bind_param("sss", $username, $email, $hashedPwd);
$stmt->execute();
}
because you didn't need to do that with 15 lines of code, when you only needed 5.

password_verify() doesnt seem to work with database

This is my login verify. Im echoing everything for debugging
<?php
echo $email = $_POST['email'];
echo $password = $_POST['password'];
include 'conn.php';
$sql = $conn->prepare("SELECT id, password FROM user_info WHERE email=?");
$sql->bind_param('s',$email);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
$sql->close();
echo $hash = $row['password'];
if (password_verify($password, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
$conn->close();
?>
My SignUp page
<?php
include 'conn.php';
$name = $_POST['first_name']." ".$_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = $conn->prepare("INSERT INTO `user_info` (`email`, `name`, `password`, `gender`) VALUES (?, ?, ?, ?)");
$sql->bind_param('sssi', $email, $name, $password, $gender);
$sql->execute();
$sql->close();
$conn->close();
?>
Snapshot of my database
Every time it just outputs to password invalid.

How to update data in mysql after you logged in

After the person logged in to the session, i want to update his bio. Its a small project for about 20 people so I am not worried about sql injection.
There is two pages, the first being the signup/login. and the other one being the profile. i want to update the bio on the profile page. after i click the update button, it redirects to the correct page but ther is no change in the database.
//This is the signup server side
$db = mysqli_connect('localhost', 'root', '', 'pt');
if (isset($_POST['reg_user'])) {
$firstname = mysqli_real_escape_string($db, $_POST['firstname']);
$lastname = mysqli_real_escape_string($db, $_POST['lastname']);
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = $_POST['password_1'];
$password_2 = $_POST['password_2'];
$sex = mysqli_real_escape_string($db, $_POST['sex']);
if ($sex == "Select Sex:") {
array_push($errors, "select male or female");
}
$user_check_query = "SELECT * FROM users WHERE username='$username' OR
email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
if (count($errors) == 0) {
$password = md5($password_1);
$query = "INSERT INTO users (firstname, lastname, username, email,
password, sex, bio)
VALUES('$firstname', '$lastname','$username', '$email', '$password',
'$sex','')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
header('location: profile.php');
}
}
//here is the code on the profile side.
?>
<?php
session_start();
if (isset($_SESSION['username'])) {
if (isset($_POST['update_user'])) {
$bio = mysqli_real_escape_string($db, $_POST['bio']);
$query = "UPDATE users SET bio='$bio' WHERE username=$username";;
header('location: profileclient.php');
}
}
?>
<form method="post" action="profileclient.php">
<div class="input-group">
<input type="text" name="bio">
</div>
<div class="input-group">
<button type="submit" class="button" name="update_user"> update!
</button>
</div>
</form>
Your code has multiple problems. Let me list them out.
Never store passwords in clear text or using MD5/SHA1! Only store password hashes created using PHP's password_hash(), which you can then verify using password_verify(). Take a look at this post: How to use password_hash and learn more about bcrypt & password hashing in PHP
Warning: You are wide open to SQL Injections and should really use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input, especially that which comes from the client side. Even when your queries are executed only by trusted users, you are still in risk of corrupting your data.
Always exit() after header('Location: ...');
It looks like you have forgot to start your session in the sign-up file. Add session_start().
You need to enable error reporting for mysqli. Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Here is your code fixed:
<?php
session_start();
//This is the signup server side
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = mysqli_connect('localhost', 'root', '', 'pt');
if (isset($_POST['reg_user'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$email = $_POST['email'];
$password_1 = $_POST['password_1'];
$password_2 = $_POST['password_2'];
$sex = $_POST['sex'];
if ($sex == "Select Sex:") {
array_push($errors, "select male or female");
}
$user_check_query = "SELECT * FROM users WHERE username=? OR email=? LIMIT 1";
$stmt = mysqli_prepare($db, $user_check_query);
mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = mysqli_fetch_assoc($result);
if ($user) {
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
if (!$errors) {
$password_hashed = password_hash($password_1, PASSWORD_DEFAULT);
$query = "INSERT INTO users (firstname, lastname, username, email, password, sex, bio)
VALUES(?, ?, ?, ?, ?, ?,'')";
$stmt = mysqli_prepare($db, $query);
mysqli_stmt_bind_param($stmt, 'ssssss', $firstname, $lastname, $username, $email, $password_hashed, $sex);
mysqli_stmt_execute($stmt);
$_SESSION['username'] = $username;
exit(header('location: profile.php'));
}
}
//here is the code on the profile side.
?>
<?php
session_start();
if (isset($_SESSION['username'])) {
if (isset($_POST['update_user'])) {
$query = "UPDATE users SET bio=? WHERE username=?";
$stmt = mysqli_prepare($db, $query);
mysqli_stmt_bind_param($stmt, 'ss', $_POST['bio'], $_SESSION['username']);
mysqli_stmt_execute($stmt);
exit(header('location: profileclient.php'));
}
}
?>
<form method="post" action="profileclient.php">
<div class="input-group">
<input type="text" name="bio">
</div>
<div class="input-group">
<button type="submit" class="button" name="update_user"> update!
</button>
</div>
</form>
Try using 'id' attribute in your input tag alongside the 'name' attribute
Try this code in your profile section
<?php
session_start();
if (isset($_SESSION['username'])) {
if (isset($_POST['update_user'])) {
$bio = mysqli->escape_string($_POST['bio']);
$query = "UPDATE users SET bio='$bio' WHERE username='$username'" or die(mysqli_error());
$result = $db->query($query);
header('location: profileclient.php');
}
}
?>
<form method="post" action="profileclient.php">
<div class="input-group">
<input type="text" name="bio" id="name">
</div>
<div class="input-group">
<button type="submit" class="button" name="update_user"> update! </button>
</div>
</form>

PDO insert not working correctly

When I login it's suppose to insert, but instead does nothing.. On my register php it inserts data to accounts, but when i insert data into online it won't work..
PS- I'm new to PDO so I don't know what i'm doing wrong
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
include('../php/dbConnect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'SELECT * FROM `accounts` WHERE username = ?';
$queryprepare = $conn->prepare($query);
$queryprepare->bindParam(1, $username, PDO::PARAM_STR);
$queryprepare->execute();
$row = $queryprepare->fetch();
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['age'] = $row['age'];
$_SESSION['image'] = $row['image'];
$check_row = 'SELECT * FROM `online` WHERE username = ?';
$check_row_fetch = $conn->prepare($check_row);
$check_row_fetch->bindParam(1, $username, PDO::PARAM_STR);
$check_row_fetch->execute();
$number_of_rows = $check_row_fetch->rowCount();
if($number_of_rows != 0) {
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
$online_insert = 'INSERT INTO online (username, name, age, image) VALUES (?, ?, ?, ?)';
$online_insert_fetch = $conn->prepare($online_insert);
$online_insert_fetch->bindParam(1, $SESSION['users'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(2, $SESSION['name'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(3, $SESSION['age'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(4, $SESSION['image'], PDO::PARAM_STR);
$online_insert_fetch->execute();
echo '<script type="text/javascript">','redirect();','</script>';
}
}
else{
echo("Wrong Credentials");
}
?>

field name entered are still inserted in database. (PHP)

I have this validation code:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM tablename");
while($row=mysql_fetch_array($tbl))
{
$name=$_POST['name'];
$lname=$_POST['lname'];
$add=$_POST['add'];
$age=$_POST['age'];
$contact=$_POST['contact'];
$email=$_POST['email'];
$user=$_POST['user'];
$pass=$_POST['pass'];
if(($name!="")&&($lname!="")&&($add!="")&&($age!="")&&($contact!="")&& ($email!="")&&($user!="")&&($pass!=""))
{
if ($_POST['user']==$row['username'])
{
header("location: /register.php?codeErr2=1");
}
else
{
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact,email, username, password) VALUES ('".$_POST['name']."','".$_POST['lname']."','".$_POST['add']."','".$_POST['age']."','".$_POST['contact']."','".$_POST['email']."','".$_POST['user']."','".$_POST['pass']."')");
}
}
else
{
header("location: /register.php?codeErr=1");
}
}
This validation is for my registration form, If all the fields are filled up it will check if the username that the user enters is already on the database or not, else, it will get an error message. If the username is already on the database, an error message will be outputted else it will proceed to the next page and all values will be inserted on the database. The problem is that whenever I enter the username which was already on the database, it still accepts the username. I can't find anything wrong with my validation code. Can someone help me out what could be the possible problem here? Thank you in advance. :)
You should check for username and die after the redirect:
$tbl=mysql_query("SELECT * FROM tablename WHERE `username` = '".mysql_real_escape_string($_POST['user'])."'");
$row = mysql_fetch_assoc($tbl);
if ($_POST['user'] == $row['username']){
header("location: /register.php?codeErr2=1");
die;
}
You code is SQL injection vulnerable:
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM tablename WHERE `username` = '".mysql_real_escape_string($_POST['user'])."'");
$row = mysql_fetch_assoc($tbl);
if ($_POST['user'] == $row['username']){
header("location: /register.php?codeErr2=1");
die;
}
$name= $_POST['name'];
$lname= $_POST['lname'];
$add = $_POST['add'];
$age = $_POST['age'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$user = $_POST['user'];
$pass = $_POST['pass'];
if(($name!="") && ($lname!="") && ($add!="") && ($age!="") && ($contact!="") && ($email!="") && ($user!="") && ($pass!="")){
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact, email, username, password)
VALUES
('".mysql_real_escape_string($name)."','".mysql_real_escape_string($lname)."','".mysql_real_escape_string($add)."','".mysql_real_escape_string($age)."',
'".mysql_real_escape_string($contact)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($user)."',
'".mysql_real_escape_string($pass)."')");
} else {
header("location: /register.php?codeErr=1");
die;
}
As a side note you should move to PDO or MySQLi as mysql_* functions are deprecated.
Here is a nice tutorial and here is an example:
$db = new PDO('mysql:host=localhost;dbname=nnx;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION))
$stmt = $db->prepare("SELECT * FROM `tablename` WHERE `username` = :username");
$stmt->execute(array(':username' => $_POST['user']));
$row_count = $stmt->rowCount();
if($row_count){
header("location: /register.php?codeErr2=1");
die;
}
if(($name!="") && ($lname!="") && ($add!="") && ($age!="") && ($contact!="") && ($email!="") && ($user!="") && ($pass!="")){
$stmt = $db->prepare("INSERT INTO `tablename`(`name`, `lastname`, `address`, `age`, `contact`, `email`, `username`, `password`) VALUES (:name, :lname, :address, :age, :contact, :email, :username, :password)");
$stmt->execute(array(':name' => $_POST['name'], ':lname' => $_POST['lname'], ':address' => $_POST['add'], ':age' => $_POST['age'], ':contact' => $_POST['contact'], ':email' => $_POST['email'], ':username' => $_POST['user'], ':password' => $_POST['pass']));
} else {
header("location: /register.php?codeErr=1");
die;
}
This way your are sql injection free.
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$name=$_POST['name'];
$lname=$_POST['lname'];
$add=$_POST['add'];
$age=$_POST['age'];
$contact=$_POST['contact'];
$email=$_POST['email'];
$user=$_POST['user'];
$pass=$_POST['pass'];
if(($name!="")&&($lname!="")&&($add!="")&&($age!="")&&($contact!="")&& ($email!="")&&($user!="")&&($pass!=""))
{
$tbl=mysql_query("SELECT * FROM tablename where username = '{$user}'");
$num_rows = mysql_num_rows($tbl);
if($num_rows > 0){
header("location: /register.php?codeErr2=1");
} else {
while($row=mysql_fetch_array($tbl))
{
$value=mysql_query("INSERT INTO tablename(name, lastname, address, age, contact,email, username, password) VALUES ('".$_POST['name']."','".$_POST['lname']."','".$_POST['add']."','".$_POST['age']."','".$_POST['contact']."','".$_POST['email']."','".$_POST['user']."','".$_POST['pass']."')");
}
}
} else {
header("location: /register.php?codeErr=1");
}
?>

Categories