I would very much like to know how to add a random salt to the following code, I've been looking around the Internet, but I haven't figured it out yet, at least not the "PDO way" (if it even makes a difference)?
Anyway, I've got this code:
login.php:
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="loginForm">
<?php
// form is submitted, check if acess will be granted
if($_POST){
try{
// load database connection and password hasher library
require 'libs/DbConnect.php';
require 'libs/PasswordHash.php';
// prepare query
$query = "select email, password from users where email = ? limit 0,1";
$stmt = $con->prepare( $query );
// this will represent the first question mark
$stmt->bindParam(1, $_POST['email']);
// execute our query
$stmt->execute();
// count the rows returned
$num = $stmt->rowCount();
if($num==1){
//store retrieved row to a 'row' variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// hashed password saved in the database
$storedPassword = $row['password'];
// salt and entered password by the user
$salt = "whatever";
$postedPassword = $_POST['password'];
$saltedPostedPassword = $salt . $postedPassword;
// instantiate PasswordHash to check if it is a valid password
$hasher = new PasswordHash(8,false);
$check = $hasher->CheckPassword($saltedPostedPassword, $storedPassword);
/*
* access granted, for the next steps,
* you may use my php login script with php sessions tutorial :)
*/
if($check){
echo "<div>Access granted.</div>";
}
// $check variable is false, access denied.
else{
echo "<div>Access denied. <a href='login.php'>Back.</a></div>";
}
}
// no rows returned, access denied
else{
echo "<div>Access denied. <a href='login.php'>Back.</a></div>";
}
}
//to handle error
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
// show the registration form
else{
?>
<!--
-where the user will enter his email and password
-required during login
-we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
-->
<form action="login.php" method="post">
<div id="formHeader">Website Login</div>
<div id="formBody">
<div class="formField">
<input type="email" name="email" required placeholder="Email" />
</div>
<div class="formField">
<input type="password" name="password" required placeholder="Password" />
</div>
<div>
<input type="submit" value="Login" class="customButton" />
</div>
</div>
<div id='userNotes'>
New here? <a href='register.php'>Register for free</a>
</div>
</form>
<?php
}
?>
</div>
</body>
</html>
register.php
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="loginForm">
<?php
// save the username and password
if($_POST){
try{
// load database connection and password hasher library
require 'libs/DbConnect.php';
require 'libs/PasswordHash.php';
/*
* -prepare password to be saved
* -concatinate the salt and entered password
*/
$salt="whatever";
$password = $salt . $_POST['password'];
/*
* '8' - base-2 logarithm of the iteration count used for password stretching
* 'false' - do we require the hashes to be portable to older systems (less secure)?
*/
$hasher = new PasswordHash(8,false);
$password = $hasher->HashPassword($password);
// insert command
$query = "INSERT INTO users SET email = ?, password = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['email']);
$stmt->bindParam(2, $password);
// execute the query
if($stmt->execute()){
echo "<div>Successful registration.</div>";
}else{
echo "<div>Unable to register. <a href='register.php'>Please try again.</a></div>";
}
}
//to handle error
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
// show the registration form
else{
?>
<!--
-where the user will enter his email and password
-required during registration
-we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
-->
<form action="register.php" method="post">
<div id="formHeader">Registration Form</div>
<div id="formBody">
<div class="formField">
<input type="email" name="email" required placeholder="Email" />
</div>
<div class="formField">
<input type="password" name="password" required placeholder="Password" />
</div>
<div>
<input type="submit" value="Register" class="customButton" />
</div>
<div id='userNotes'>
Already have an account? <a href='login.php'>Login</a>
</div>
</div>
</form>
<?php
}
?>
</div>
</body>
</html>
Now, how do I create a randomly generated salt?
Use password_hash (as of PHP 5.5). It will take care of everything for you.
There is a compatibility wrapper for older PHP versions.
Related
I was following a tutorial on creating a cms but the instructor used md5 for the passwords, I am trying to change it to use password_hash instead. The password used in my sql database does use password_hash but I am getting confused as to how to verify it in my login page.
I've tried changing the md5 to password_hash in the login page but this does not work and I've also tried password_verify. I know these should be used but can't figure out where and what I should change.
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
<title>CMS Tutorial</title>
<link rel="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS
<br />
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
}else{
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
//$password = md5($_POST['password']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
if (empty($username) or empty($password)){
$error = 'All fields are required!';
}else{
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
//user entered correct details
}else{
//user entered false details
$error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
<title>CMS Tutorial</title>
<link rel="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS
<br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo $error; ?></small>
<br /><br />
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
<html>
<?php
}
?>
At the moment I am just getting the
"incorrect details" error
that I have created and if I use password_verify I get the
"all fields are required error"
To check the password you must use password_verify() function, instead of password_hash().
Some time ago I wrote a canonical example, Authenticating a user using PDO and password_verify().
As you can see, the code is extremely simple: you just need to select the password and then compare it using password_verify()
$stmt = $pdo->prepare("SELECT * FROM users WHERE user_name = ?");
$stmt->execute([$_POST['username']]);
$user = $stmt->fetch();
if ($user && password_verify($_POST['password'], $user['password']))
{
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
}else{
$error = 'Incorrect details!';
}
I'm currently making a website with a friend using HTML/CSS/PHP. Everything has been going perfectly until we decided to transfer the files over to an online host for free to test it out. Unfortunately, it was not working properly. We have a database setup for the login system and whenever we attempt to register on the online host DB, it sends an error saying the page is not working.
I've tried multiple online hosts including 000webhost, however, all of them had similar issues. I've put them in the htdocs folder in the FTP server files as well, made the database with proper configuration, and made sure the user, database name, password, and host all were the same. Nothing works and it has me absolutely stump.
$host = "sql400.hitcluster.com";
$dbusername = "epiz_239708";
$dbpassword = "password";
$dbname = "epiz_23959708_House";
// Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
?>
session_start();// Starting Session
//if session exit, user nither need to signin nor need to signup
if(isset($_SESSION['login_id'])){
if (isset($_SESSION['pageStore'])) {
$pageStore = $_SESSION['pageStore'];
header("location: $pageStore"); // Redirecting To Profile Page
}
}
//Register progess start, if user press the signup button
if (isset($_POST['signUp'])) {
if (empty($_POST['fullName']) || empty($_POST['email']) || empty($_POST['newPassword'])) {
echo "Please fill up all the required field.";
}
else
{
$fullName = $_POST['fullName'];
$email = $_POST['email'];
$password = $_POST['newPassword'];
$hash = password_hash($password, PASSWORD_DEFAULT);
// Make a connection with MySQL server.
include('config.php');
$sQuery = "SELECT id from account where email=? LIMIT 1";
$iQuery = "INSERT Into account (fullName, email, password) values(?, ?, ?)";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($sQuery);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
$rnum = $stmt->num_rows;
if($rnum==0) { //if true, insert new data
$stmt->close();
$stmt = $conn->prepare($iQuery);
$stmt->bind_param("sss", $fullName, $email, $hash);
if($stmt->execute()) {
echo 'Register successfully, Please login with your login details';}
} else {
echo 'Someone already registered with this discord username';
}
$stmt->close();
$conn->close(); // Closing database Connection
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Register</title>
<link rel="stylesheet" href="auth.css">
</head>
<body>
<div class="rlform">
<div class="rlform rlform-wrapper">
<div class="rlform-box">
<div class="rlform-box-inner">
<form method="post" oninput='validatePassword()'>
<p>Let's create your account</p>
<div class="rlform-group">
<label>Username</label>
<input type="text" name="fullName" class="rlform-input" required>
</div>
<div class="rlform-group">
<label>Discord Username and Identifier</label>
<input type="text" name="email" class="rlform-input" placeholder = "EX: DiscordUser#1234" required>
</div>
<div class="rlform-group">
<label>Password</label>
<input type="password" name="newPassword" id="newPass" class="rlform-input" required>
</div>
<div class="rlform-group">
<label>Confirm password</label>
<input type="password" name="conformpassword" id="conformPass" class="rlform-input" required>
</div>
<button class="rlform-btn" name="signUp">Sign Up
</button>
<div class="text-foot">
Already have an account? Login
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function validatePassword(){
if(newPass.value != conformPass.value) {
conformPass.setCustomValidity('Passwords do not match.');
} else {
conformPass.setCustomValidity('');
}
}
</script>
</body>
</html>
The code above shows the config.php and the register.php which are the error messages I receive from. It depends on the host, but I'd either get an error message saying the page isn't working or nothing at all happens. I'd expect the registration page to state that the user has registered successfully which later on proceeds to you being able to login, however, nothing even happens nor does the information I registered with show up on the database (phpMyAdmin). Hopefully you can help me out.
I am new to PHP, but I am working on a login system for this website. I am currently working on the account creation page and I can not get the .php file to post to my database. Can anyone out there give me a hand? My code is below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EDAViewer Login Console</title>
<link rel="stylesheet" href="/CSS/styles.css">
</head>
<body>
<div class="container">
<div class="main-wrapper">
<div class="header">
<header>
<img src="/Assets/BGLogo.png" alt="EDAViewer Logo">
<img src="/Assets/accountCreation.png" alt="Create Account" class="console-img">
</header>
</div>
<div class="login-container">
<fieldset class="login-form">
<form class="form" action="newAccount.php" method="POST">
<ul>
<li>
<label for="username">Username</label>
<input type="text" name="username" required>
</li>
<li>
<label for="password">Password</label>
<input type="text" name="password" required>
</li>
<li>
<label for="verify-password">Verify Password</label>
<input type="text" name="verify-password" required>
</li>
<li>
<input type="submit" value="Create Account">
</li>
</ul>
</form>
</fieldset>
</div>
</div>
</div>
<div class="footer">
<footer>
<p>Copyright © 2018 EDA Technologies, Ltd</p>
</footer>
</div>
</body>
</html>
here is the PHP:
<?PHP
$dbConn = mysqli_connect("ServerName(Changed it to post here) ", "UserName",
"Password", DBname);
if (mysqli_connect_errno()){
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}else{
printf("Host information: %s\n", mysqli_get_host_info($mysqli));
mysqli_close($dbConn);
}
$username = mysqli_real_escape_string($dbConn, $_POST['username']);
$password = $_POST['password'];
$vpass = $_POST['verify-password'];
if($password !=== $vpass){
echo "Your passwords did not match."
}else{
$userSQL = "INSERT INTO user_list (username)
VALUES ('".$username"')";
$passSQL = "INSERT INTO user_list (password)
VALUES ('".$password."')";
$res = mysqli_query($dbConn, $userSQL, $passSQL);
if ($res === TRUE){
echo "Account Created";
}else{
printf("There was an error creating this account: %s\n", mysqli_error($dbConn));
}
mysqli_close($dbConn);
}
?>
The problem I am running into is everytime I press the submit button, I get the CANNOT POST newAccount.php error. What am I doing wrong? I have been trying to get this to work on my own for the last 2 days. I even included the database connection code to this file to see if I referenced it wrong in the beginning.
I am not sure if this is the problem causing it not to work in your script, but it seems like that a ; is missing here
if($password !=== $vpass){
echo "Your passwords did not match."; //<---
}else{
$userSQL = "INSERT INTO user_list (username)
VALUES ('".$username"')";
$passSQL = "INSERT INTO user_list (password)
VALUES ('".$password."')";
Also,you should not do <input type=text ... for your password. Instead, you should use <input type=password>
EDIT: just found out another mistake that may cause your script not to work...
According to http://php.net/manual/zh/language.operators.comparison.php, there're only !== and != in php,
you should do if($password !== $vpass) or if($password != $vpass) instead of if($password != $vpass)
note: (sth!==sth mean !(sth===sth) and sth!=sth mean !(sth==sth))
EDIT 2: as stated by Robin Zigmond, you shouldn't save the password with plain text in your database... you could use
$passSQL = "INSERT INTO user_list (password)
VALUES ('".password_hash($password)."')";
instad to make it safer. When you are logging in, you can use
if(password_verify($_POST['password'], $encrypted_password)){
//correct password
}else{
//incorrect password
}
to verify the password.
More information can be found on http://php.net/manual/en/function.password-hash.php & http://php.net/manual/en/function.password-verify.php
Just use
if($password != $vpass){
echo "Your passwords did not match.";
}else{
$userSQL = "INSERT INTO user_list (username)
VALUES ('".$username"')";
$passSQL = "INSERT INTO user_list (password)
VALUES ('".$password."')";
}
I think you have an issue with the directory.
You can refer here
Also, you are sending multiple queries using mysqli_query() instead of this use mysqli_multi_query() you can find more here
I hope this will solve your issue.
I have a question about my code. The problem is that when i say echo $collumB than he shows the student_city. that is in my database but i want that it shows the decrypted password. It just shows the wrong data
(there is an another page where i encrypt the password but i need the decrypted password echo'ed
<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style-login.css">
</head>
<body>
<div id="main">
<h1>Login using PDO</h1>
<div id="login">
<h2>Login</h2>
<hr/>
<form action="" method="post">
<label>Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Password :</label>
<input type="password" name="stu_ww" id="ww" required="required" placeholder="Please Enter Your Password"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
<?php
//require ("encrypt.php");
if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';
$pdo = "college";
$student_email = $_POST["stu_email"];
$encrypt_key = "4ldetn43t4aed0ho10smhd1l";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=college","root","$password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query
$statement = $dbh->prepare("SELECT student_email, student_city, AES_DECRYPT(student_password, '$encrypt_key')
AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC");
// Assign and execute query
$statement->bindParam(':student_email', $student_email, PDO::PARAM_STR);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$statement->execute();
// Get data
while($row = $statement->fetch()) {
echo "1 ,";
//$columnA_value = $row['student_city'];
$columnB_value = $row['student_password'];
}
echo "2 ,";
echo $columnB_value;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
</body>
</html>
SELECT student_email, student_city, CAST(AES_DECRYPT(student_password, '$encrypt_key') AS char(50)) AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC;
Try to explicitly cast it to string. You can change the '50' according to your requirement.
Also your echo is outside while loop, hence it will print only last record if there are more than 1 records.
So i followed a tutorial that shows how to login,
But i made a username and password in my phpmyadmin, But everytime when i try to login it says: Username or Password not found this is the code;
<!--Begin webshop WOOOH-->
<?php
session_start();
//DB configuration Constants
include("class.php");
//PDO Database Connection
try {
$databaseConnection = new PDO('mysql:host='._HOST_NAME_.';dbname='._DATABASE_NAME_, _USER_NAME_, _DB_PASSWORD);
$databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if(isset($_POST['submit'])){
$errMsg = '';
//username and password sent from Form
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if($username == '')
$errMsg .= 'You must enter your Username<br>';
if($password == '')
$errMsg .= 'You must enter your Password<br>';
if($errMsg == ''){
$records = $databaseConnection->prepare('SELECT id,username,password FROM tbl_users WHERE username = :username');
$records->bindParam(':username', $username);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($password, $results['password'])){
$_SESSION['username'] = $results['username'];
header('location:dashboard.php');
exit;
}else{
$errMsg .= 'Username and Password are not found<br>';
}
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<title>Webshop 2016</title>
</head>
<body>
<div id="wrapper">
<div id="header">
<ul>
<li>Info</li>
<li>Login</li>
<li>Webshop</li>
<li>Home</li>
</ul>
</div>
<!--Main content!-->
<div id="content">
<div align="center">
<div style="width:300px; border: solid 1px #006D9C; " align="left">
<?php
if(isset($errMsg)){
echo '<div style="color:#FF0000;text-align:center;font-size:12px;">'.$errMsg.'</div>';
}
?>
<div style="background-color:#006D9C; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style="margin:30px">
<form action="" method="post">
<label>Username :</label><input type="text" name="username" class="box"/><br /><br />
<label>Password :</label><input type="password" name="password" class="box" /><br/><br />
<input type="submit" name='submit' value="Submit" class='submit'/><br />
</form>
</div>
</div>
</div>
</div>
<div id="footer">
Footer
</div>
</div>
</body>
</html>
This is the class.php (the connection file)
<?php
define('_HOST_NAME_', 'localhost');
define('_USER_NAME_', 'root');
define('_DB_PASSWORD', '####');
define('_DATABASE_NAME_', 'ws_webshop');
//PDO Database Connection
try {
$databaseConnection = new PDO('mysql:host='._HOST_NAME_.';dbname='._DATABASE_NAME_, _USER_NAME_, _DB_PASSWORD);
$databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Does anyone see the problem?
the user and pass is demo / demo but he says theres no Username or password found...
From the docs:
Returns TRUE if the password and hash match, or FALSE otherwise.
If you did not use password_hash() to insert the password in the database your check using password_verify() attempt here:
if(count($results) > 0 && password_verify($password, $results['password'])){
will always fail because the function expects a plain password to compare against the hashed value of the password. for more insight on PHP's password functions read this post.
In addition you may find yourself wanting to limit passwords and you really shouldn't do that.