Can someone please take a look at this block of code? I am very new to the PDO method, for some reason this keeps causing a 500 error whenever I submit.
I have narrowed it down to this:
Could it be this part? $hash = $stmt['hash'];
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
If you need more info please ask I will be happy to supply anything I can.
You need to fetch the result of the query to have it accessible. I'm not sure this is your issue, I'd think $hash would just be set to Resource Id#x, not what you want but not a 500. Here's how to fetch (http://php.net/manual/en/pdostatement.fetch.php) though
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
//if you will only be getting back one result you dont need the while or hashes as an array
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$hashes[] = $result['hash'];
}
Here's a thread on enabling error reporting PHP production server - turn on error messages
Also you don't have to bind to pass values with the PDO. You also could do
$stmt = $db->prepare("SELECT * FROM Login WHERE username= ?"); // Prepare the query
$stmt->execute(array($username));
Your code is really messy. Just to help you with start point:
if (empty($response['error'])) {
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hash = $row['hash'];
if(password_verify($password, $hash)) {
$_SESSION['username'] = $username;
$_SESSION['userid'] = $stmt['ID'];
} else {
$response['error'][] = "Your password is invalid.";
}
} else {
$response['error'][] = "No User is related to the Username";
}
} else {
$response['error'][] = "Username is not set!";
}
}
Related
Everthing seems to work except inserting data stmt.
I've added closing the connection and adding closing the statement.
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = 'Not all fields were entered<br><br>';
else
{
$stmt = $connection->prepare('SELECT * FROM members WHERE user=?');
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows)
$error = 'That username already exists<br><br>';
else
{
$hashedPwd = password_hash($pass, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO members (user, pass) VALUES (?,?)");
$stmt->bind_param("ss", $user, $hashedPwd);
$stmt->execute;
$stmt->close();
die('<h4>Account created</h4>Please Log in.</div></body></html>');
}
}
}
$connection->close();
I can expect the code to recognize if a user exists. However, I can not expect the database to be updated with a new user.
Placing error_reporting(E_ALL); at the top of the page will show that there is problem with the $stmt->execute;
$stmt->execute; should be stmt->execute();
I'm trying to do an execution of a query and see if it goes well, but right now it doesn't enter the IF or ELSE.
I had it on mysqli procedural and all worked flawlessy now I'm trying to change it to object oriented and it won't enter inside if/else.
if(isset($_POST['submit']))
{
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email=? AND Password=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email,$password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1)
{
?>
<script type="text/javascript">
alert("INSIDE");
</script>
<?php
$row = $result->fetch_assoc();
if(isset($_POST['remember']))
{
$_SESSION["remember"] = "1";
}
$_SESSION["username"] = $row['Username'];
$_SESSION['check'] = "1";
$_SESSION['ID'] = $id;
$_SESSION['permission'] = $row['Admin'];
header("Location: dashboard.php");
exit;
}
else
{
?>
<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>
<?php
exit;
}
$stmt->close();
}
Thank you all.
You should be using
$stmt->bind_result($col1, $col2 ...);
and
$result = $stmt->fetch();
in order to access the data from the query, rather than
$conn->query($stmt);
(an example is provided at https://secure.php.net/manual/en/mysqli-stmt.fetch.php). Note that for this to work you will need to specify the column names you want to fetch from the database, rather than using * in your SQL query, and for each column data is fetched from in the query, you should have a variable for in the fetch() parameters, so for example, something as follows should work (note these may not match the names of your database columns):
$email = $_POST["email"];
$password = md5($_POST["password"]);
$stmt = $conn->prepare("SELECT ID, Name FROM Users WHERE Email=? AND Password=?");
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($id, $name);
$stmt->fetch();
$stmt->close();
echo $id . ': ' . $name;
Updated Answer
You are very close. Use $result = $stmt->get_result(); instead of $result = $stmt->query; to check to see if the query returned a result or not.
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email = ? AND Password = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows !== 0){
if(isset($_POST['remember'])){
$_SESSION["remember"] = "1";
}
$_SESSION['check'] = "1";
$_SESSION['ID'] = $row['ID'];
header("Location: dashboard.php");
exit();
}else{
echo
'<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>';
exit();
}
$stmt->close();
As several have already stated in their comments do not use MD5 for password hashes. PHP has it's own built in functions for handling passwords. Please research Password_has() and Password_verify(). Spend the time to research and implement these now instead of later. It will save you time.
EDIT: To clarify, I am unable to extract the hashed password from my database using prepared statements.
I'm trying to create a login system that uses prepared statements, password_hash and password_verify.
I have created the registering form that creates the user, with the hashed password using password_hash($_POST['password'], PASSWORD_DEFAULT);
This works properly.
However, I am now stuck on creating the login form.
I am trying to get the password hash that gets stored when a user registers but I cannot get it to work with prepared statements.
This is what I currently have.
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
}
}
?>
How do I use the data that I got from the select query? And how do I use it to verify the password?
I tried:
$stmt->store_result();
$stmt->bind_result($loginUsername, $hash);
That only stored the username, but not the password hash and I have no clue why.
Verifying the password would use this?
password_verify($password, $hash);
UPDATE
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$result = $stmt->get_result();
// Fetch the query results in a row
while($row = $result->fetch_assoc()) {
$hash = $row['user_password'];
$username = $row['user_name'];
}
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
Read this PHP MANUAL.Try this:
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$stmt->bind_result($user_name,$hash);
$stmt->store_result();
// Fetch the query results in a row
$stmt->fetch();
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
This is how I created my login system:
$stmt = mysqli_prepare($link,"SELECT user_email,user_password,user_firstname,user_lastname,user_role,username FROM users WHERE user_email=?");
mysqli_stmt_bind_param($stmt,"s",$email);
mysqli_stmt_execute($stmt);
confirmQuery($stmt);
mysqli_stmt_bind_result($stmt,$user_email,$user_password,$user_firstname,$user_lastname,$user_role,$username);
mysqli_stmt_store_result($stmt);
mysqli_stmt_fetch($stmt);
if(mysqli_stmt_num_rows($stmt) == 0)
relocate("../index.php?auth_error=l1");
else{
if(password_verify($password,$user_password)){
$_SESSION['userid'] = $user_email;
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $user_firstname;
$_SESSION['lastname'] = $user_lastname;
$_SESSION['role'] = $user_role;
if(isset($_POST['stay-logged-in']))
setcookie("userid", $email, time() + (86400 * 30), "/");
relocate("../index.php?auth_success=1");
}else
relocate("../index.php?auth_error=l2");
}
mysqli_stmt_close($stmt);
I can't get this to work. I am new to working with prepared statements so i i'm kinda 50/50 on what i'm doing.
Upon registration, the password is hashed with password_hash($pass,PASSWORD_DEFAULT)
Now, i'm trying to get my login page to function with this but i dont know where / how to write it with the password_verify()
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE BINARY username=? AND password=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if($num_rows == 1){
$rows = $result->fetch_assoc();
if(password_verify($password, $rows['password'])){
$_SESSION['loggedin'] = $username;
$_SESSION['country'] = $rows['country'];
$_SESSION['email'] = $rows['email'];
$_SESSION['avatar'] = $rows['u_avatar'];
$_SESSION['is_gm'] = $rows['is_gm'];
$_SESSION['user_lvl'] = $rows['user_lvl'];
$_SESSION['totalposts'] = $rows['post_total'];
$_SESSION['totalcoins'] = $rows['coins_total'];
$_SESSION['totalvotes'] = $rows['vote_total'];
$_SESSION['secquest'] = $rows['sec_quest'];
$_SESSION['secanswer'] = $rows['sec_answer'];
$_SESSION['join_date'] = $rows['join_date'];
header("Location: /index.php");
exit();
}
} else {
echo "<p class='error_msg'>No accounts could be found with the given credentials.</p>";
}
$stmt->free_result();
$stmt->close();
$db->close();
I would assume that the password verify would before if($num_rows == 1) but as i said, i have no idea.
Your query is essentially:
SELECT * FROM users WHERE username=username AND password_hash=plain_text_password
This isn't going to work. If you're relying on PHP password hashing, you can't do a password comparison on the SQL level. Retrieve the password hash from the database then do the password_verify (exclude the password=?) in your WHERE arguments.
i have a php login script which is accessed with a simple form:
<?php
session_start();
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay;', $user, $pass);
if(isset($_SESSION['loggedin'])){
echo "1"; //already logged in
}
else{
$username = $_POST['username'];
$password = sha1($_POST['password']);
$ucheck = $pdo->prepare('SELECT * FROM user WHERE username = ?');
$ucheck->bindValue(1, $username);
$ucheck->execute();
if($ucheck->fetch(PDO::FETCH_OBJ)){
$stmt = $pdo->prepare('SELECT * FROM user WHERE username = ? AND password = ?');
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $password);
if($stmt->fetch(PDO::FETCH_OBJ)){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $row['username'];
$_SESSION['loggedin'] = 'YES';
$_SESSION['location'] = $row['location'];
echo "2"; //logged in
}
else{
echo "3"; //password incorrect
}
}
else{
echo "4"; //user does not exist
}
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
but when i attempt to run it using an account that i just created and have confirmed to exist within the database, i get no response from this script. i would expect it to echo 2 given that the login information is correct, but i get nothing
can anyone suggest what ive done wrong here?
It looks like you forgot to execute() the statement:
if($ucheck->fetch(PDO::FETCH_OBJ)){
$stmt = $pdo->prepare('SELECT * FROM user WHERE username = ? AND password = ?');
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $password);
// Execute it!!!
if ($stmt->execute()) {
$row = $stmt->fetch(PDO::FETCH_OBJ);
if ($row) {
// And don't call fetch() again, since you would already have advanced
// the record pointer in the first fetch() above. If one record was returned,
// this one would always be FALSE.
//$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $row['username'];
$_SESSION['loggedin'] = 'YES';
$_SESSION['location'] = $row['location'];
echo "2"; //logged in
}
// else execute failed...
}
are you sure session.use_cookies = 1 in php.ini?
please make sure have name is PHPSESSION cookie.