I am looking to check the username and password that are entered are equal to the username and password stored in mysql database.
I have used password_hash() to hash the password and stored them into table. But I don't know, how to check if they are the same or not.
HTML
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
<span class="error">* <?php echo $usernameErr;?></span>
<br><br>
Password: <input type="password" name="password">
<span class="error">* <?php echo $passwordErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
error_reporting(E_ALL | E_STRICT);
$servername = "localhost";
$serverUsername = "root";
$serverPassword = "";
// Create connection
$conn = mysqli_connect($servername, $serverUsername, $serverPassword);
mysqli_select_db($conn, 'users');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
if (isset($_POST["submit"])) {
$query = mysqli_prepare($conn, "SELECT * FROM user_logons WHERE Username = ? AND Password = ?");
mysqli_stmt_bind_param ($query , 'ss' , $username , $password);
mysqli_stmt_execute($query);
$username = mysqli_real_escape_string($conn, $_POST["username"]);
$password = password_hash($_POST["password"], PASSWORD_BCRYPT);
mysqli_stmt_close($query);
}
$usernameErr = $passwordErr = "";
mysqli_close($conn);
?>
Also, do I have to escape the password input if it is hashed?
You need to get the input password hashed again and before binding it with your prepare statement. You need to make sure, you are using same encryption method, which was used for storing.
$username = mysqli_real_escape_string($conn, $_POST["username"]);
$password = password_hash($_POST["password"], PASSWORD_BCRYPT);
mysqli_stmt_bind_param ($query , 'ss' , $username , $password);
mysqli_stmt_execute($query);
Edited:
As suggested by #Devon in comment, you could also use password_verify
Related
i have a problem in sending my form values to mysql database i readed all other topics and i did what they wrote but i didn't get what i want please help me :(
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "13838383";
$dbname = "users";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
?>
<?php
include("../includes/functions.php");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../public/stylesheets/style.css" type="text/css">
<title>Our WebPage</title>
</head>
<body>
<center>
<form action="input.php" method="post">
<fieldset>
<legend>Register</legend>
<span>UserName: </span><br />
<input type="text" name="username" placeholder="USERNAME"><br /><br />
<span>PassWord: </span><br />
<input type="text" name="lastname" placeholder="PASSWORD"><br /><br />
<input type="button" name="submit" value="submit"><br /><br />
<fieldset>
</form>
</center>
<?php
?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$addUserQuery = "INSERT INTO users (username, password) VALUES ({$username}, {$password});";
$added = mysqli_query($connection, $addUserQuery);
if ($added) {
echo '<br>Input data is successful';
} else {
echo '<br>Input data is not valid';
}
}
?>
</body>
</html>
and my problem is i don't know know what should i enter in action attribute in form tag thanks please help
Simply put, your variables aren't quoted, so your query is being turned into this (If someone submitted 1337user as the username, and P#ssw0rd as the password):
INSERT INTO users (username, password) VALUES (1337user, P#ssw0rd);
When it should be:
INSERT INTO users (username, password) VALUES ('1337user', 'P#ssw0rd');
Bind your variables instead: How can I prevent SQL injection in PHP?
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$addUserQuery = mysqli_prepare($connection, "INSERT INTO users (username, password) VALUES (?, ?)");
mysqli_stmt_bind_param($addUserQuery, "ss", $username, $password);
$added = mysqli_stmt_execute($addUserQuery);
if ($added) {
echo '<br>Input data is successful';
} else {
echo '<br>Input data is not valid';
}
}
Basic question but I keep failing. Have checked out similar topics but didn't get closer to the solution, so please don't redirect me just point out what I'm missing. Thank you.
<?php
$hashed_password = "";
$con = mysqli_connect("localhost", "root", "", "testTable");
if (isset($_POST["reg_button"])){
$password = ($_POST["reg_password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = mysqli_query($con, "INSERT INTO user VALUES('', '$hashed_password')");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>register</title>
</head>
<body>
<form action="register.php" method="POST">
<input type="password" name="reg_password" placeholder="Password">
<br><br>
<input type="submit" name="reg_button" value="Register">
</form>
<br>
<form action="login.php" method="POST">
<input type="password" name="login_password" placeholder="Password">
<br><br>
<input type="submit" name="login_button" value="Login">
</form>
</body>
</html>
This is the registering part and it is working flawlessly. The provided password is getting hased and stored in the DB.
<?php
include "register.php";
$con = mysqli_connect("localhost", "root", "", "testTable");
if(isset($_POST["login_button"])){
$password = password_verify($_POST["login_password"], $hashed_password);
$checkDB = mysqli_query($con, "SELECT * FROM user WHERE password = '$password'");
$checkLogin = mysqli_num_rows($checkDB);
if($checkLogin == 1){
$row = mysqli_fetch_array($checkDB);
echo "Welcome";
}
else {
echo "Password incorrect";
}
}
?>
This is the login part and it always fails. I suspect the following snippet to be the culprit:
$password = password_verify($_POST["login_password"], $hashed_password);
but have no idea how to fix it.
Any help would be great. Thank you!
UPDATED CODE:
register.php:
<?php
$hashed_password = "";
$name = "";
$con = mysqli_connect("localhost", "root", "", "testTable");
if (isset($_POST["reg_button"])){
$password = ($_POST["reg_password"]);
$name = ($_POST["reg_name"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = mysqli_query($con, "INSERT INTO user VALUES('', '$name','$hashed_password')");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>register</title>
</head>
<body>
<form action="register.php" method="POST">
<input type="text" name="reg_name" placeholder="Name">
<br><br>
<input type="password" name="reg_password" placeholder="Password">
<br><br>
<input type="submit" name="reg_button" value="Register">
</form>
<br>
<form action="login.php" method="POST">
<input type="text" name="login_name" placeholder="Name">
<br><br>
<input type="password" name="login_password" placeholder="Password">
<br><br>
<input type="submit" name="login_button" value="Login">
</form>
</body>
</html>
login.php:
<?php
include "register.php";
$con = mysqli_connect("localhost", "root", "", "testTable");
if(isset($_POST["login_button"])){
$name = $_POST['login_name'];
$password = $_POST['login_password'];
$checkDB = mysqli_query($con, "SELECT * FROM user WHERE name = '$name'");
$passwordField = null;
while($getRow = mysqli_num_rows($checkDB)){
$passwordField = $getRow['password']; // Get hashed password
}
if(password_verify($password, $passwordField)){
echo('Correct');
}else{
echo('Wrong');
}
}
?>
Below from where do you get $hashed_password?Even if you included register.php,it doenst do anything,since those values are not set.
$password = password_verify($_POST["login_password"], $hashed_password);
You first need to get it from the db.
Second, password_verify returns true or false so even if $hashed_password is set,$password would be a boolean.
You can do this via while loop and mysqli_fetch_array(). That must solve your problem.: [UPDATED]
<?php
$con = mysqli_connect("localhost", "root", "", "testtable");
if(isset($_POST["login_button"])){
// $password = password_verify($_POST["login_password"], $hashed_password);
$password = $_POST['password'];
$checkDB = mysqli_query($con, "SELECT * FROM user");
while($getRow = mysqli_fetch_array($checkDB)){
$passwordRow = $getRow['password'];
}
if(password_verify($password, $passwordRow) === TRUE){
echo('Welcome');
}else{
echo('Wrong credentials');
}
}
?>
I am fiddling around with mysql, PHP, and phpMyAdmin and I am making a short little test login and register system. Only problem is for some reason, the register button takes me to the login page, which it's supposed to, but localhost crashes for some reason. Any help?
Edit: You can test it out too if you would like. My Site: http://localhost/
index.php
<head>
<meta charset="utf-8">
<title>Test Site</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<form action="login/logreg.php" method="post" accept-charset="utf-8">
<label>Username: </label><input type="text" name="username" value="" placeholder="Username">
<br><br>
<label>Password: </label><input type="password" name="password" value="" placeholder="Password">
<br><br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
logreg.php
<?php
$cookie_name = "loggedin";
$servername = "localhost";
$username = "root";
$password = "H2124130E63C8D14871";
$database = "webserver";
$conn = mysqli_connect($servername, $username, $password $database);
if (!$conn) {
die("Database Connection Failed: ".mysqli_connect_error());
}
if (isset($_POST['login']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
$cookie_value = $user;
setcookie($cookie_name, $cookie_value, time() + (180), "/");
header("Location: personal.php");
}
else
{
echo "Username Or Password Is Incorrect!";
}
}
else if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash');";
$result = mysqli_query($conn, $sql);
}
?>
personal.php
<?php
$cookie_name = "loggedin";
if (isset($_COOKIE[$cookie_name]))
{
$cookie_value = $_COOKIE[$cookie_name];
echo "Welcome To Your Personal Area $cookie_value!";
echo 'Logout';
}
?>
logout.php
<?php
setcookie("loggedin", "val", time() - (120), "/");
header("Location: index.php");
?>
You missed a comma here:
$conn = mysqli_connect($servername, $username, $password $database);
Trying to simply register, although file is named as Login.html/.php
My HTML form in Login.html :
<!DOCTYPE html>
<html>
<head>
<title>Register/ Login</title>
<link rel="stylesheet" type="text/css" href="Assets/bootstrap.css">
<script src="Assets/jquery.min.js"></script>
<script src="Assets/bootstrap.min.js"></script>
</head>
<body>
<form action="Login.php" method="post">
<fieldset>
<legend>Register:</legend>
Username : <input type="text" name="Username"> <br>
Password : <input type="password" name="Password"> <br>
<input type="submit"><br>
</fieldset>
</form>
</body>
</html>
Have set up the MySQL side of the code and run it as well, it works fine.
The PHP file, Login.php :
<?php
$userErr = $passErr = "";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed");
$Username = $_POST['Username'];
$Password = $_POST['Password'];
echo("Reached 1. <br>");
$stmt = "INSERT INTO Login (Username, Password) VALUES ('$Username', '$Password')";
$result = mysqli_query($conn, $stmt);
if($result) {
echo("Registered Successfully!");
}
mysqli_close($conn);
?>
When I enter the details and submit, the code for Login.php is displayed, with the url being: (file:///C:/xampp/htdocs/Login.php)
Also, Login.html was run on localhost, i.e., url being:
(http://localhost/Login.html)
I can guess you are browsing your Login.html with
file:///C:/xampp/htdocs/Login.html
But you have to use like this
http://localhost/Login.html
I am trying to create a login page using wamp server kindly help me with the following code
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db ="test"; //database name
if(isset($_POST['username']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql ="SELECT * FROM users WHERE username ='$username' AND password ='$password'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result==1))
{
echo "logged in successfully"."<br/>";
}
else
{
echo "invalid password or username retry";
}
}
?>
<html>
<head>
<title>login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="login" method="post" action="login.php">
Username <input type="text" name="username">
<br/><br/>
Password <input type="password" name="password">
<br/><br/>
<input type="submit" value="login" name="submit">
</form>
</body>
</html>
I think you had read some wrong articles and messed up .The correct code should be like this
$host = "localhost";
$user = "root";
$pass = "";
$db ="test"; //database name
// This line connects to DB
$con = mysqli_connect($host, $user, $pass,$db) or die ("Please check your server connection.") ;
if(isset($_POST['username']))
{
// use mysqli_real_escape_string to prevent SQL Injection
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
//write a query to select
$sql ="SELECT * FROM users WHERE username ='".$username."' AND password ='".$password."'";
//execute the written query using mysqli_query()
$result = mysqli_query($con,$sql);
//----------------------^----------- This is the missed parameter
//check the no of rows returned
if(mysqli_num_rows($result) == 1) { echo "logged in successfully"; }
else { echo "invalid password or username retry"; }
}
The line
if(mysqli_num_rows($result==1)) // You are passing boolean parameter here.
is incorrect
It should be:
if(mysqli_num_rows($result)==1) // You are passing result set here, which is expected.