The function password_verify() consistently yields a negative result

As a beginner, I recently attempted to develop a login system using PHP and MySQL. I successfully created a registration form and added a few users, but encountered issues when trying to create the login form. Every time I tried to log in, it displayed an error message stating "Your username or password is incorrect!". I have shared my code below and would greatly appreciate any assistance. My apologies if this question seems too basic :/

<?php
    session_start();
    include '.\includes\functions\db.php';
?>

<?php
    $username = strtolower(mysqli_real_escape_string($db, $_POST['username']));
    $password = strtolower(mysqli_real_escape_string($db, $_POST['password']));

    $sql        = "SELECT * FROM users WHERE username = '$username' ";
    $result     = mysqli_query($db, $sql);
    $row        = mysqli_fetch_assoc($result);
    $hash_pwd   = $row['password'];
    echo $hash_pwd;
    echo $password;
    $hash       = password_verify($password, $hash_pwd);

    if ($hash ==0) {
        header("Location: ./index.php?error=check");
        exit();
    }else {
        $sql = "SELECT * FROM user WHERE username = '$username' AND password = '$hash_pwd'";
        $result = mysqli_query($db, $sql);
        if (mysqli_num_rows($result) == 0) {
            echo "Your username or password is incorrect!";
        }else {
            $_SESSION['id'] = $row['id'];
            $_SESSION['username'] = $row['username'];
        }
        //header("Location: ./index.php");
    }
?>

Here is my registration page:

<?php
//This Page is for registration of users
?>

<?php
// includes for all functions
include '.\includes\functions\db.php';

?>

<?php
//extracting data from the form
if(isset($_POST["register"])){
    $username   = $_POST['username'];
    $firstname  = $_POST['firstname'];
    $lastname   = $_POST['lastname'];
    $email      = $_POST['email'];
    $password   = $_POST['password'];
    $date       = date('Y-m-d H:i:s');

    //Sanitizing received data
    $username               = strtolower(mysqli_real_escape_string($db, $username));
    $firstname              = strtolower(mysqli_real_escape_string($db, $firstname));
    $lastname               = strtolower(mysqli_real_escape_string($db, $lastname));
    $email                  = strtolower(mysqli_real_escape_string($db, $email));
    $password               = strtolower(mysqli_real_escape_string($db, $password));
    $encryptedpassword      = password_hash($password, PASSWORD_DEFAULT);

    //Checking for duplicate emails
    $sql        = "SELECT email FROM users WHERE email='$email'";
    $result     = mysqli_query($db, $sql);
    $row        = mysqli_num_rows($result); 

    //Checking for duplicate usernames
    $sql2       = "SELECT username FROM users WHERE username='$username'";
    $result2    = mysqli_query($db, $sql2);
    $row2       = mysqli_num_rows($result2); 

    //Handling duplicate cases
    if($row > 0 && $row2 > 0){
        echo "Sorry...This email id and username is already taken!!!";
    } elseif ($row > 0 ) {
        echo "Sorry...This email id is already taken!";
    } elseif ($row2 > 0) {
        echo "Sorry...This Username is already taken!";
    } else {
        $query  = mysqli_query($db, "INSERT INTO users (username, firstname, lastname, password, email, regdate) VALUES
        ('$username', '$firstname', '$lastname', '$encryptedpassword', '$email', '$date')");
        if($query){
            echo "Thank You! you are now registered.";
        }
    }
}

?>

Answer №1

My code was throwing an error because I mistakenly used the condition password = '$hash_pwd' in my where clause. After retrieving the row with the specified username and checking the password using PHP, everything worked as expected. It seems that passwords hashed with the password_hash() function in PHP cannot be easily retrieved and verified like encrypted passwords. Thank you to everyone who responded with suggestions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an Error when using Jquery Ajax to call session variables

I have been attempting to retrieve session variables using a Jquery Ajax call, but I keep encountering the "Unexpected token < in JSON" error in the jquery response. Below is my Jquery code - $( document ).ready(function() { $.ajax({ url: "mys ...

Python event-driven long polling server (similar to the current PHP server)

I have a straightforward php script (currently running on xampp) for a long polling server, but I am interested in converting it to Python and creating a Python server instead. Despite my limited experience with Python, especially in the realm of web serve ...

What steps do I need to take in order to integrate an mpg video onto my

I am in need of embedding mpg (dvd compliant mpeg2) movie files onto my webpage. Unfortunately, I do not have the ability to convert these videos into any other format. This webpage is solely for personal use, so any solution would be greatly appreciated. ...

Is there a way to retrieve bookmarks (TOC) from a PDF document using technologies such as NodeJS, ReactJS, or PHP?

I'm sure most people have noticed that when you open a PDF in the browser or Acrobat PDF reader, a bookmarks tab appears like the one shown here: https://i.stack.imgur.com/obFer.png If the PDF doesn't have any bookmarks, the list will be empty. ...

"Eliminate any post elements that do not contain content

Upon receiving an array in the POST request with 2 fields, I extract data from a MySQL table based on the first field to display. However, if the second field in the array is empty, I do not want it to be displayed. Below is the code snippet: <p class= ...

When an AJAX call is made during a PHP session that has timed out

I am working on an AJAX form that handles data authentication. In the event of a session timeout, I need to implement a redirect to the login page. How can I go about achieving this? Here is an excerpt from my simplified server-side code: function doExecu ...

What is the reason for imagecrop removing the transparency from the image?

Whenever I try to manipulate an image with a white background by making the white color transparent, the resulting image loses its transparency after cropping. I have attempted different approaches like cropping first and then adjusting the transparency, b ...

Ways to track the visit data for different languages in Google Analytics when the language is not included in the URL

On my website, I track Google Analytics by adding the tracking code to the header. The standard implementation of GA tracking is as follows: ga('create', 'UA-483951-1', 'auto'); ga('send', 'page ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Adding a watermark to a PDF using ImageMagick's composite function while also enhancing the

I am trying to find ways to add a watermark to a PDF file. I have come across 2 solutions - using ghostscript and imagemagick composite. I found that ghostscript cannot be called from the command line, so I opted for the command 'composite' inste ...

Error initializing AWS Transcribe PHP API 3.0 - Unable to Initialize API

I'm currently working on setting up the API for AWS Transcribe, but I'm facing some confusion with the documentation. Below is my code: <?php require 'aws-api/aws-autoloader.php'; $client = new Aws\TranscribeService\T ...

PHP code that generates a drop-down list using a foreach iteration

all I'm encountering a slight issue with trying to create a dynamic drop down list. Here's the code I've written: <select name='categoryID' > <?php foreach( $categories as $category)?> <option value="<?p ...

Increasing the markdown percentage for variable items during a sale

I am attempting to display a discount percentage alongside the price on a WooCommerce website. Here is the code I have used for both the standard price and the sale price: // Add save percentage next to sale item prices. add_filter( 'woocommerce_get ...

Encountering issues with mySQL query execution

I'm not well-versed in PHP or mySQL, so I could really use your assistance. I have a php script with a function that generates a json containing all the records from a database table: public function select($table, $wheres = null) { $connect = $t ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

What steps should I take to resolve a 500 (Internal Server Error) issue?

Recently, I encountered a server error issue while requesting data from the server using my React client. Unfortunately, the server failed to respond properly and I traced the problem back to my Sequelize Database. exports.createMemeber = (req, res) => ...

Show the JSON data from the server in a table format

Is there a way to neatly display data received from an Ajax response within a table format? Below is the structure of the table: <table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table"> ...

Is it advisable to add the CodeIgniter model object to global variables?

Just curious if anyone has any input. I'm currently in the process of developing a complex Codeigniter application and considering storing some model objects in $GLOBALS. This would allow me to use something similar to global $post; or global $wpdb i ...

Looking to optimize PHP foreach loop for faster processing speed

I am currently working on integrating MS based web applications with my php application using SOAP to fetch the data. I have a file system structure in xml format that I convert to an object. Each document has an ID and path, and I have built methods to de ...

I'm encountering an issue with PHP MyAdmin SQL where I am unable to make alterations to my MySQL table. The error code #1064 keeps

I am attempting to modify an existing table using the PHP MyAdmin SQL query. I inserted the following code: ALTER TABLE file ADD orderid int(11)NOT NULL ADD title varchar(200) NOT NULL ADD description VARCHAR(700) NOT NULL ADD make VARCHAR(100) NOT NULL AD ...