php password_verify still not working - php

I have read many articles on this password_hash and has applied as much as I can if not all the things I read about it
Still the password_verify still refuses to authenticate values no matter how much I tried. PHP Version 5.61.6 and SQL version 5.7.9
any form of help is appreciated, am already exhausted from trying many string combinations
<!DOCTYPE html>
<html>
<head>
<title>Administrator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?PHP
//.......all variables are collected from html form....
$conn = mysqli_connect("localhost", "uname", "pword", "dbname");
mysqli_set_charset($conn, 'utf8');
//.......`SN` column has the unique attribute
$sql = "SELECT * FROM Sign_Up WHERE `SN`=$sn";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$date = date('Y-m-j g:i:s');
//.......idgen is a function previously defined
$id = idgen();
//.......prints $id before hashing....
echo $id."<BR>";
$id = password_hash('$id', PASSWORD_DEFAULT);
//......string length before storing
echo strlen($id)."<BR>";
//......table columns
$f = $row["FirstName"];
$l = $row["LastName"];
$bn = $row["BusinessName"];
$ba = $row["BusinessAddress"];
$sq = "INSERT INTO Distributors (`FirstName`, `LastName`, `BusinessName`, `BusinessAddress`) VALUES ('$f', '$l', '$bn', '$ba')";
$res = mysqli_query($conn, $sq);
}
}
?>
</body>
</html>
And the code for verifying the hash is
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?PHP
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn, 'utf8');
//.....phone number has a unique attribute
$sql = "SELECT `ID` FROM Distributors WHERE `PhoneNumber`='number'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result1= mysqli_num_rows($result);
$look = mysqli_fetch_array($result)['ID'];
print $look."<BR>";
$look = trim($look);
print $look."<BR>";
print strlen($look)."<BR>";
//......all print statements yields expected results and hashed password is stored
//......in VARCHAR (255)...I also tried CHAR
$ver = password_verify('user input data', '$look');
if ($ver) {
print "ok";
}
else {
print "no";
}
?>
</body>
</html>

Use php variables without any quote or inside double quotes, "":
$id = password_hash($id, PASSWORD_DEFAULT); // no quotes around $id
$ver = password_verify('user input data', "$look"); // double quotes around $look
Single quote strings are not parsed i.e. treated as literal strings while double quoted strings are parsed and therefore variables names are expanded with their values.

When hashing use:
$id = "school";
Password_hash($id);
When verifying use:
Password_verify($id, $data_from_database);

Related

autocomplete results show up but cant find uppercase letters

The autocomplete is almost working as it should, except for a problem with words that start with an Uppercase.
for example the word 'Brussels':
I will be able to find it when I start typing in the searchbox 'russels', but 'Bru...' will not be found.
looking for words starting with a lowercase is not a problem, 'brussels' will show up once i start typing 'bru'.
Also words like New York will not show up when i start tying 'York', but will when i type 'ork'.
Search.php file
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName= "vlucht";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($conn, 'utf8');
$id = $_GET['q'];
$sql = "SELECT discipline FROM overzicht where discipline like '%".$id."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["discipline"]. "\n";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php file:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#search").autocomplete("search.php");
});
</script>
</head>
<body>
Discipline : <input type="text" name="q" id="search" placeholder="Geef je discipline in">
</body>
</html>
MySQL's LIKE is usually case insensitive, unless you are using a collation (e.g. binary) where that would not be the case. Assuming that, for whatever reason, your collation is causing LIKE to be case sensitive, here is one way you may phrase your query to behave the way you want:
$id = $_GET['q'];
$disc = "%" . strtolower($id) . "%";
$sql = "SELECT discipline FROM overzicht WHERE LOWER(discipline) LIKE ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $disc);
$stmt->execute();
Note that I am switching to using prepared statements with mysqli, which avoid things like SQL injection, to which your current script is prone.

PHP to delete a row from mysql database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I have a PHP that I am unable to get it to work. Its function is to connect to my db and delete the input email address from the database. But for some reason, the result is always "Data Not Deleted". I am sure of all the details like db connect details and columns names etc. still the code doesn't work.
Code:
<?php
// php code to Delete data from mysql database
if(isset($_POST['delete']))
{
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "newsletter";
// get id to delete
$email = $_POST['email'];
// connect to mysql
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// mysql delete query
$query = "DELETE FROM `email_user` WHERE `email` = $email";
$result = mysqli_query($connect, $query);
if($result)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}
mysqli_close($connect);
}
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP DELETE DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="unsub.php" method="post">
ID TO DELETE: <input type="text" name="email" required><br><br>
<input type="submit" name="delete" value="Clear Data">
</form>
</body>
</html>
Please point out what I am doing wrong in here?
Thanks
You need to add quotes around $email in your query as it is a string.
$query = "DELETE FROM `email_user` WHERE `email` = '$email'";
Note:- Your code is wide-open for SQL INJECTION.You have to use prepared statements
Help reference:-
mysqli::prepare
PDO::prepare
Try modifying the query to following:
"DELETE FROM `email_user` WHERE `email` = '$email'"

Access denied for user 'root'#'localhost' (using password: NO)

I'm using a simple form to do a database query. The database is accessed via password which I've included in the code. I'm not sure why I keep hitting the error on the string escape and the undefined variable $query = htmlspecialchars($query);
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="Search2.php" method="POST">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
<?php
if (isset($_POST['query']))
$query = $_POST['query'];
if (!empty($query))
$query = $_POST['query'];
// gets value sent over search form
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT LastName, FirstName FROM Staff
WHERE (`LastName` LIKE '%".$query."%') OR (`FirstName` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['LastName']."</h3>".$results['FirstName']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
</body>
</html>
The issue here is that you've invoked a mysqli object with your credentials, however, later you try to execute with the mysql_ procedural method. You don't have a connection there. You need to stick with the mysqli object. Furthermore, you should use prepared statements to handle your user input on SQL queries.
Remove these, we don't need to do sanitization for prepared statements:
//BYE!
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
Now let's use the mysqli object and OOP prepared methods. However, first we need to construct our like statements as our query's variables aren't executed, you can't concatenate %?% directly into the prepared() statement.
$query = '%'.$query.'%';
$stmt = $mysqli->prepare("SELECT LastName, FirstName FROM Staff
WHERE LastName LIKE ? OR FirstName LIKE ?");
Now we can bind the parameters to our $stmt object.
$stmt->bind_param('ss', $query, $query);
Let's execute it now and get our data back.
$result = $stmt->execute();
Then we can loop:
while ($row = $result->fetch_assoc()) {
echo "<p><h3>".$result['LastName']."</h3>".$result['FirstName']."</p>";
}
Edit
You also don't need to escape your column names with a backtick because:
They don't have - in the name
They aren't reserved special words in MySQL.
make sure your PHP version is below 7.0 as stated here:
http://php.net/manual/en/function.mysql-real-escape-string.php
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()

Convert to mysqli Prepared Statements from Procedural ones

I need help with the follow code to change it from Procedural to Prepared Statement. I will do my best to code it:
Default procedural script MYSQLI default
<?php
$conn = mysqli_connect ('localhost', 'gggggg', 'gggggg') ;
mysqli_select_db ($conn, 'ggggg');
$anti_injection = mysqli_real_escape_string($_GET['user']);
$sql = "SELECT * FROM profiles WHERE username =".$anti_injection);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($sql)) {
$username = stripslashes($row['username']);
$age = stripslashes($row['age']);
$gender = stripslashes($row['gender']);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
CATEGORY <?php echo $username; ?>
TITEL <?php echo $age; ?>
CONTENT <?php echo $sex; ?>
</body>
</html>
<?php
}
?>
#
NOW MY CHANGES TO STATEMENTS HOPE IT WORKS
#
$query = $sql->prepare("SELECT * FROM profiles WHERE `username`=?")
$prep->bind_param("s",$anti_injection);
$prep->execute();
Thats all I know for the SELECT in a safe mode but then with the MYSQLI_FETCH_ARRAY I really dont know it it will work and hopefully if there is a chance to keep the script the way I like with the echos between the HTML BODY page
Some Example On How it must be done?
First off, I highly recommend you not mix procedural with objects. It will get confusing much faster that way. Consider using the mysqli object instead.
$mysqli = new mysqli('localhost'...);
Second, you're close but, as I said, you're mixing objects and procedural so the way you've changed it won't work. Plus you're bouncing variables all over the place (if you ran your changes raw it would fail). Assuming you switch to the mysqli object as outlined above, you can do this
$prep = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?");
$prep->bind_param("s",$anti_injection);
$prep->execute();
Now, the next part is tricky. You have to have mysqlnd installed to do this but it's the best way to get your results back. If you run this and get an error about get_result being missing, you're not running mysqlnd
$result = $prep->get_result();
while($row = $result->fetch_array()) {
//Your HTML loop here
}
I provide a script, based on yours, that i have commented, tested, and uses procedural 'mysqli'. Hopefully, it will clarify things.
<?php
/* (PHP 5.3.18 on XAMPP, windows XP)
*
* I will use the procedural 'mysqli' functions in this example as that is
* what you seem familiar with.
*
* However, the 'object oriented' style is preferred currently.
*
* It all works fine though :-)
*
* I recommend PDO (PHP Data Objects) as the way to go for Database access
* as it provides a 'common' interface to many database engines.
*/
// this is an example 'select' parameter -- how this value gets set is up to you...
// use a form, get parameter or other, it is not important.
$bindparamUsername = 'user_2'; // example!!!!
// connect to the database...
$dbConnection = mysqli_connect('localhost', 'test', 'test'); // connect
mysqli_select_db($dbConnection, 'testmysql'); // my test database
// the SQL Query...
// the '?' is a placeholder for a value that will be substituted when the query runs.
// Note: the ORDER of the selected Columns is important not the column names.
//
// Note: The number of selected columns is important and must match the number of
// 'result' bind variables used later.
$sql = "SELECT username, age, gender FROM profiles WHERE username = ?";
// DB engine: parse the query into an internal form that it understands
$preparedQuery = mysqli_prepare($dbConnection, $sql);
// bind an actual input PHP variable to the prepared query so the db will have all required values
// when the query is executed.
//
mysqli_stmt_bind_param($preparedQuery, 's', $bindparamUsername);
// run the query...
$success = mysqli_execute($preparedQuery);
// You can only bind which variables to store the result columns in AFTER the query has run!
//
// Now bind where any results from the query will be returned...
// There must be as many 'bind' variables as there are selected columns!
// This is because each column value from the query will be returned into the
// 'bound' PHP variable.
//
// Note: You cannot bind to an array. You must bind to an individual PHP variable.
//
// I have kept the same names but they are only of use to you.
$fetchedRow = array( 'username' => null,
'age' => null,
'gender' => null);
/*
* Note: order of columns in the query and order of destination variables in the 'bind' statement is important.
*
* i.e. $fetchedRow[username] could be replaced with variable $firstColumn,
* $fetchedRow[age] could be replaces with variable $secondColumn
* and so on...
*
* There must be as many bind variables as there are columns.
*/
mysqli_stmt_bind_result($preparedQuery, $fetchedRow['username'],
$fetchedRow['age'],
$fetchedRow['gender']);
/*
* Note: if you use the 'Object Oriented' version of 'mysqli': All of this is 'hidden'
* but still happens 'behind the scenes'!
*
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
<?php // each 'fetch' updates the $fetchedRow PHP variable... ?>
<?php while (mysqli_stmt_fetch($preparedQuery)): ?>
<br />
CATEGORY <?php echo $fetchedRow['username']; ?>
<br />
TITEL <?php echo $fetchedRow['age']; ?> <br />
CONTENT <?php echo $fetchedRow['gender']; ?> <br />
<?php endwhile ?>
</body>
</html>
If you'r learning I encourage you to use Object Oriented Style
The Manual is the first resource where you can find the most accurate information. Following your example:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Here you avoid the warning undefine variable if $_GET['user'] ins't set
$user = isset($_GET['user']) ? $_GET['user'] : NULL;
$row = array();
//Checking if $user is NULL
if(!empty($user)){
// Prepared statement, stage 1: prepare
if (!($stmt = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("s", $user)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
//Fetching the result
$res = $stmt->get_result();
$row = $res->fetch_assoc();
/* explicit close recommended */
$stmt->close();
}else{
//do this code if $user is null
}
//Printing out the result
echo '<pre>';
print_r($row);
echo '</pre>';
you can do it like that
$link = mysqli_connect("localhost", "my_user", "my_password", "db"); //Establishing connection to the database , this is alias of new mysqli('')
$query="SELECT * FROM profiles WHERE `username`=?";
$stmt = $link->prepare($query);
$stmt->bind_param("s",$anti_injection); // binding the parameter to it
$stmt->execute(); //Executing
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // we used MYSQLI_ASSOC flag here you also can use MYSQLI_NUM or MYSQLI_BOTH
{
//Do stuff
}

My first PHP/MySQL db, no output to the webpage?

I'm a noob to PHP/mySQL and I'm enjoying it, but I'm stuck... I'm in the process of developing my first database driven website. I've created the database, the tables... loaded one table in particular with content in an attempt to pull data from it via PHP. If you go to my website live via the browser, there is a navigation system that seems to work but, it's not loading content from the db table. It's just blank content with a nav system that changes the page in the address bar but blank content. I've provided the code along with a image shot of the table in my database I'm trying to GET the data from. The db table i'm getting from is called vls_pages. It is also the table featured in the image. I'm hoping someone can point me to getting this to function correctly. Thank you everyone
index.php CODE:
<?php
// Load Setup document:
include
('_config/setup.php'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?></title>
<link rel="stylesheet" type="text/css" href="_css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="nav_main">
<?php include('_template/nav_main.php'); ?>
</div>
<div class="body_header">
<?php get_page_name($dbc, $pg); ?>
</div>
<div class="content">
<?php get_page_body($dbc, $pg); ?>
</div>
<div class="footer">
<?php include('_template/footer.php'); ?>
</div>
</div>
</body>
</html>
setup.php CODE:
<?php
## Setup Document
// host(or location of the database), username, password, database name
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "***************";
$username = "***************";
$password = "***************";
//Connecting to your database
$dbc = #mysqli_connect($hostname, $username, $password) OR DIE ("Unsuccessful.");
// Check connection
if (mysqli_connect_errno($dbc))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
include('_functions/snippets.php');
if ($_GET['pgname'] == '') {
$pg = 'home';
}
else {
$pg = $_GET['pgname'];
}
$page_title = get_page_title($dbc, $pg);
?>
snippets.php CODE:
<?php
// Snippets; Functions
function get_page_title ($dbc, $pg) {
$query = "SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
return $page['pgtitle'];
#mysqli_close($dbc);
}
function get_page_name ($dbc, $pg) {
$query = "SELECT pgname FROM vls_pages WHERE pgname = '$pg' AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
echo '<h1>'.$page['pgname'].'</h1>';
#mysqli_close($dbc);
}
function get_page_body ($dbc, $pg) {
// the database connection, our query
$query = "SELECT * FROM vls_pages WHERE pgbody = '$pg' AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
echo '<div class="content">'.$page['pgbody'].'</div>';
#mysqli_close($dbc);
}
?>
You're closing the database connection at the end of each function. So after you get the page title, the database connection closes.
Remove this line from the end of every function in setup.php:
#mysqli_close($dbc);
Then add that line to the end of index.php to close the connection after the page is done processing:
<?php
mysqli_close($dbc);
?>
This will solve the major issue described in the question. For the sake of completeness, you should also follow the recommendations in the comments area of the question. Specifically, the SQL query in get_page_title() should have "WHERE" instead of "AND", and remove the "#" error suppression, especially while you're learning.
there is a mistake in your query, you forgot to keep where condition please replace the following code
$query = "SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1";
with
$query = "SELECT pgtitle FROM vls_pages where pgstatus = 1 LIMIT 1";
As per the SELECT syntax in the manual on the MySQL.com website.
The syntax is SELECT select_expr FROM table_references WHERE where_condition equals
Now, this line is using the AND clause:
SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1
which should be using the WHERE clause, such as:
SELECT pgtitle FROM vls_pages WHERE pgstatus = 1 LIMIT 1
Consult lwitzel's answer also
Food for thought:
Do take the comments into (serious) consideration when it comes to properly sanitizing your inputs.
The use of PDO is highly recommended - PDO Tutorial

Categories