PHP PDO Declare name as variable - php

So In my project I'm trying to declare a variable so it will display their full name if logged in. I'm assuming it would be a query to fetch the data from the table but I'm unsure on how to have it make sure it get's that certain user's name and not the first name on the table
Here's my registration code.
if( $user->is_logged_in() ){ header('Location: index.php'); }
//if form has been submitted process it
if(isset($_POST['submit'])){
//very basic validation
if(strlen($_POST['username']) < 3){
$error[] = 'Username is too short.';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $_POST['username']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['username'])){
$error[] = 'Username provided is already in use.';
}
}
if(strlen($_POST['password']) < 3){
$error[] = 'Password is too short.';
}
if(strlen($_POST['passwordConfirm']) < 3){
$error[] = 'Confirm password is too short.';
}
if($_POST['password'] != $_POST['passwordConfirm']){
$error[] = 'Passwords do not match.';
}
//email validation
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//email validation
if(strlen($_POST['fullname']) < 2){
$error[] = 'Please enter a valid full name';
} else {
$stmt = $db->prepare('SELECT fullname FROM members WHERE fullname = :fullname');
$stmt->execute(array(':fullname' => $_POST['fullname']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//if no errors have been created carry on
if(!isset($error)){
//hash the password
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
//create the activasion code
$activasion = md5(uniqid(rand(),true));
try {
//insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (username,password,email,fullname,active) VALUES (:username, :password, :email, :fullname, :active)');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':fullname' => $_POST['fullname'],
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <".SITEEMAIL.">\r\n";
$additionalheaders .= "Reply-To: $".SITEEMAIL."";
mail($to, $subject, $body, $additionalheaders);
//redirect to index page
header('Location: index.php?action=joined');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
Updated with the user class:
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password FROM members WHERE username = :username');
$stmt->execute(array('username' => $username));
$row = $stmt->fetch();
return $row['password'];
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
return true;
}
}
}

Why not simply select them from the database?
Please don't mind me if I mix in a little pseudo code since I'm not very familiar with your variables.
First, you create/start a SESSION if the login credentials are correct.
if($login_credentials_correct){ //lol you know what I mean here
session_start();
$_SESSION['username'] = $_POST['username']; // or wherever it may have come from
}
Now that the session is on, you can perform a query somewhat similar to this
<?php
session_start(); // fixed
$username = $_SESSION['username'];
$stmt = $db->prepare('SELECT fullname FROM members where username= :username');
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$fullName = $row['fullName']; //I am not sure if this is the correct index.
//to make sure, use var_dump($row) and find out which index has the full name
echo $fullName; //voila.
?>
Now, this code only works if your username is unique. Lol. which site has no unique username.

Can you post your log in code? I'll try to answer with what you ave so far.
If you want users to have the ability to log in and have their data available for display do this
if(!($_SERVER['REQUEST_METHOD'] == "POST")){
//Code here for users trying to access page incorrectly
}else{
if(isset($_POST['username']) && ($_POST['username'] <= $UsernameMaxLength)){
$username=strip_tags(stripslashes($_POST['username'])); //Clean the data up
}else{
//Error handling code
}
if(isset($_POST['password']) && ($_POST['password'] <= $PasswordMaxLength)){
//I would advise you use SHA1() instead for password encryption, but I'll use what you used here
$password=$user->password_hash(strip_tags(stripslashes($_POST['password'])), PASSWORD_BCRYPT); //Clean the data up
}else{
//Error handling code
}
if(!isset($username) || !isset($password)){
//Error handling code
}else{
$stmt = $db->prepare('SELECT fullname FROM members where username= :username and password=:password');
$stmt->execute(array('username':$username,'password':$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Code here to make sure there is a row with the number given and all that
//other jazz. In this code I'll assume all went well
if(All_went_well){
//Start your session to store variables you want
session_start();
$_SESSION['fullname']=$row['fullname'];
}
}
}

In your login method, save $username as a session value under $_SESSION['loggedin'] that you can retrieve later like this...
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
return true;
}
}
Then have another method at the bottom of the file that goes something like...
public function get_username(){
if(isset($_SESSION['username'])){
return $_SESSION['username'];
}
}
Then you can call this method like $user->get_username() to get the current logged in users username. Then getting their fullname from the database would require a simple query with "WHERE username = :username". I you can add another method like this to make things easier...
public function get_fullname(){
if(issset($_SESSION['username']){
$stmt = $this->_db->prepare('SELECT fullname FROM members WHERE username = :username');
$stmt->execute(array('username' => $this->get_fullname()));
$row = $stmt->fetch();
return $row['fullname'];
}
}

Related

PHP Login Code not working - Database Connection is okay

I'm trying to set up a Register + Login for one of my Sites. The Registration process works completely fine but the Login seems to fail every time.
This is the register.php
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email =?")) {
$error = '';
$query->bind_param('s', $email);
$query->execute();
$query->store_result();
if ($query->num_rows >0) {
$error .= '<p class="error">E-Mail already registered</p>';
}
if (empty($confirm_password)) {
$error .= '<p class="error">Passwords do not match.</p>';
}
if (empty($error)) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your Registration was succesful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
}
}
$query->close();
$insertQuery->close();
mysqli_close($db);
}
?>
This is the Login.php
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']) ;
if (empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
if (empty($password)) {
$error .= '<p class="error">Please enter password.</p>';
}
if (empty($error)){
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s',$email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$SESSION["user"] = $row;
header("location: index2.php");
exit;
}else{
$error.= '<p class="error">The password is not valid.</p>';
}
}else{
$error.= '<p class="error">Wrong mail.</p>';
}
}
$query->close();
}
mysqli_close($db);
}
?>
According to Online PHP Checker my Code should be correct. There are no Errors in Console and I really don't know what exactly i did wrong. Hope someone can help me with this!
This line is the issue, I expect:
$row = $query->fetch();
According to the documentation, the fetch() function returns true, false or null - it does not return a row of data. You need to use bind_result() to map the results from the query into variables.
https://www.php.net/manual/en/mysqli-stmt.fetch.php

My code doesnt login after verify password code

Please, help me look at this code for login, I want to verify if input password matches stored harsh password. This does not work. If i comment out If (password_verify..., i will be able to login otherwise, it wont login. i dont know where i got the code wrong and it doesnt want to verify password before login
if (isset($_POST['agentlogin-btn'])) {
$username= $_POST['username'];
$password = $_POST['password'];
function Is_email($user)
{
//If the username input string is an e-mail, return true
if (filter_var($user, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
//validation
if (strlen($_POST['username']) < 1) {
$_SESSION['error'] = 'email or phone number required';
header("Location:register.php");
return;
}
if (strlen($_POST['password']) < 1) {
$_SESSION['error'] = 'password required';
header("Location:register.php");
return;
}
if (!isset($_SESSION['error'])) {
$check_email = Is_email($username);
if ($check_email) {
$sql = "SELECT * FROM agent WHERE Email= :email LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':email' => $_POST['username'],
));
} else {
$sql = "SELECT * FROM agent WHERE Phone_number= :phonenumber LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':phonenumber' => $_POST['username'],
));
}
if ($stmt->execute()) {
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$user = $result;
if (password_verify($password], $user['Password'])) {
//login success
$stmt->close();
$_SESSION['id'] = $user['User_id'];
$_SESSION['agentid'] = $user['agent_id'];
$_SESSION['firstname'] = $user['First_name'];
$_SESSION['Surname'] = $user['Surname'];
$_SESSION['phonenumber'] = $user['Phone_number'];
$_SESSION['email'] = $user['Email'];
$_SESSION['verified'] = $user['verified'];
// set flash message
$_SESSION['success'] = "You are now logged in! Continue with your upload";
header('location: profilepage.php');
return;
} else {
$_SESSION['errors'] = "Wrong username/password";
header('Location: register.php');
return;
}
}
}
}
instead of writing $stmt->execute() two times, store the result in a variable, and at second place use that variable.

How to use the encrypt password for login php [duplicate]

This question already has answers here:
How to use PHP's password_hash to hash and verify passwords
(5 answers)
Closed 1 year ago.
At first I am using md5 for hashing but then I learn that password_hash is more secured, but when I tried to use it in my website it wont work. I've tried putting the code password_verify everywhere.
When I'm trying to login it just giving me an error of password/ email combination is wrong even if it is correct. I also get the error for the password verify but when I put the correct credentials it's still giving me the error message
This is my login code
<?php
function login(){
global $db, $email, $errors;
// grab form values
$email = e($_POST['email']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($email)) {
array_push($errors, "Email is required");
}else {
$email = hsc($_POST["email"]);
}
if (empty($password)) {
array_push($errors, "Password is required");
}else{
$password = hsc($_POST["password"]);
}
// attempt login if no errors on form
if (count($errors) == 0) {
$query = "SELECT * FROM accounts WHERE email='$email' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (password_verify($password, $_POST["password"])) {
array_push($errors, "Wrong password");
}
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/admin.php');
exit(0);
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
exit(0);
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
This is my register code (There are all in the same file functions.inc.php)
function register(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $username, $email;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password']);
$password_2 = e($_POST['re-password']);
//check email if already exist on database
$check = "SELECT * FROM accounts WHERE email='$email'";
$res_e = mysqli_query($db, $check);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Name is required");
}elseif (!preg_match("/^[a-zA-Z]+( [a-zA-Z]+)*$/",$username)) {
array_push($errors, "Only letters and one space only");
}else{
$username = hsc($_POST["username"]);
}
if (empty($email)) {
array_push($errors, "Email is required");
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "The email is invalid");
}elseif (mysqli_num_rows($res_e) > 0) {
array_push($errors, "The email already taken");
}else{
$email = hsc($_POST["email"]);
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}elseif ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}else{
$password_1 = hsc($_POST["password_1"]);
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$hashpassword = password_hash($password_1, PASSWORD_DEFAULT);;//encrypt the password before
saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO accounts (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$hashpassword')";
mysqli_query($db, $query);
$_SESSION['add'] = "Added successfully";
header('location: users.php');
exit(0);
}else{
$query = "INSERT INTO accounts (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$hashpassword')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['add'] = "You are now logged in and thank you!";
header('location: index.php');
exit(0);
}
}
}
I don't know if this is also the reason that the login is not working but it is better that I put it in. This is the code for function hsc() and e()
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
// htmlspecialchars the inputs data
function hsc($val) {
$val = htmlspecialchars($val);
return $val;
}
Here is the data base photo
(By far the simplest method...)
Try this example. It uses Argon2, which is by far the safest encryption method (AFAIK)
Note that it randomly generates a different string when run, so using password_verify is mandatory unlike using sha-256 to look up the password in the database
<?php
$pwd = password_hash("my password goes here", PASSWORD_ARGON2I);
// Use $_POST instead
echo $pwd;
?>
And to verify your password:
if(password_verify($_POST['password'], $row["password"])) {
// Your code here...
}
Also, use PDP PDO, it's much safer against SQL injection attacks
<?php
$db = new PDO('mysql:host='.$servername.';dbname='.$dbname.';charset=utf8mb4', $username, $password);
try {
$query = "SELECT * from `login` WHERE `username`=:username OR `email` =:usernamea";
$stmt = $db->prepare($query);
$stmt->bindParam('username', $username, PDO::PARAM_STR);
$stmt->bindParam('usernamea', $username, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($count == 1 && !empty($row)) {
$auth_email = $row['email'];
$auth_pwd = $row['password'];
if(password_verify($_POST['password'], $auth_pwd)) {
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
$_SESSION['name'] = htmlspecialchars($row['name']);
}
else {
echo 'Invalid';
}
}
else {
echo 'Invalid';
}
}
catch (PDOException $e) { echo "Error : ".$e->getMessage(); }
?>

Problem with login i can login with any username and password

I have problem with login system i can login with any username and password i dont how to fix
if anyone can help i would be very grateful
here my login system
function userLog() {
global $connect;
if(isset($_POST['userLog'])) {
$username = trim(protect($_POST['username']));
$password = trim(protect($_POST['password']));
if(empty($username)) {
$_SESSION['message'] = '';
header('Location: index.php');
exit();
} elseif (empty($password)) {
$_SESSION['message'] = '';
header('Location: index.php');
exit();
}
$userSQL = "SELECT * FROM users WHERE username = :username";
$userLog = $connect->prepare($userSQL);
$userLog->bindValue(':username', $username);
$userLog->execute();
$userLog->fetchAll();
#PLACE FOR SELECT DATA FROM SQL TO IMPORT TO SESSION
$sql = "SELECT * FROM users";
$stm = $connect->prepare($sql);
$stm->execute();
$row = $stm->fetch();
####################################################
if($userLog) {
$_SESSION['user_id'] = $row['user_id'];#id(mysql)
$_SESSION['username'] = $row['username'];#user(mysql)
$_SESSION['email'] = $row['email'];#email(mysql)
$_SESSION['f_name'] = $row['first_name'];#fname(mysql)
$_SESSION['l_name'] = $row['last_name'];#lname(mysql)
header('Location: index.php');
exit();
} else {
}
}
}
Sorry for bad english
I couldnt go deep to create a class! you need to check for classes.
I just corrected your code as much as I can, I used bindParam instead of bindValue.
I hope you are using pdo, it show you are :) Please put session_start(); on top of your page before everything else.
function userLog() {
global $connect;
if(isset($_POST['userLog'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(empty($username)) {
$_SESSION['message'] = 'Enter username';
header('Location: index.php');
exit();
} elseif (empty($password)) {
$_SESSION['message'] = 'Enter password';
header('Location: index.php');
exit();
}else{
$sql = "SELECT * FROM users WHERE username = :username";
if($stmt = $connect->prepare($sql)){
$stmt->bindParam(':username', $param_username, PDO::PARAM_STR);
$param_username = $username;
if($stmt->execute()){
$row = $stmt->fetch();
if($row['username'] === 1){
$hashed_password = $row['password'];
$email = $row['email'];
$name = $row['f_name'];
$lastname = $row['l_name'];
$id = intval($row['user_id']);
if(password_verify($password, $hashed_password)){
session_regenerate_id();
$_SESSION["loggedin"] = true;
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['f_name'] = $name;
$_SESSION['l_name'] = $lastname;
header('Location: index.php');
exit();
}else{
$_SESSION['message'] = 'wrong password';
}
}else{
$_SESSION['message'] = 'wrong username';
}
}else{
$_SESSION['message'] = 'User not found';
}
}else{
$_SESSION['message'] = 'Something went wrong';
}
}
}
}
I let you to do redirections to your error page
UPDATE : This is a simple class example, Search for proper way creating classes.
class userLog {
/** #var object $connect Copy of PDO connection */
private $connect;
/** #var object of the logged in user */
private $user;
/** #var string error msg */
private $msg;
public function __construct($connect) {
$this->connect = $connect;
}
public function login($username,$password){
$stmt = $this->connect->prepare('SELECT * FROM users WHERE username = ? ');
$stmt->execute([$username]);
$user = $stmt->fetch();
if(password_verify($password,$user['password'])){
$this->user = $user;
session_regenerate_id();
$_SESSION['user']['user_id'] = $user['user_id'];
$_SESSION['user']['fname'] = $user['fname'];
$_SESSION['user']['lname'] = $user['lname'];
$_SESSION['user']['email'] = $user['email'];
return true;
}else{
$this->msg = 'Invalid login information';
//you can change ajax response to session error
return false;
}
}
}
Usaqe : $handle = new userLog($connect);
Note this function requires ajax to return response.
Here you are not checking for any password so of course anyone can login, you should fix it like this:
$userSQL = "SELECT * FROM users WHERE username = :usr AND password = :pwd";
$userLog = $connect->prepare($userSQL);
$userLog->bindValue(':usr', $username);
$userLog->bindValue(':pwd', $password);
$userLog->execute();
$users = $userLog->fetchAll();
if(count($users) == 0) {
// fail here, no one to login
exit();
} elseif(count($users) > 1) {
// Found more than one user, this should not happen, maybe fail.
}
If this check pass the user is logged in and furthermore $users[0] holds your user information

password_verify keeps bringing back false

ok so ive got password_hash working on one of my pages.
I'm wondering how would i apply password_verify to the following code:
function selectUser($conn, $username, $password)
{
$query = "SELECT username, password FROM login WHERE password = :password AND username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $password);
$stmt->execute();
if ($row = $stmt->fetch()) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
echo "Welcome, you are now logged in as " . $username;
return true;
}
else {
//echo "Your details were not found";
return false;
}
tried it myself and its been very confusing to me.
thank you
also got this:
if(!isset($_POST["Login"]))
{
header("Location:new-user.php");
}
$username=trim($_POST['username']);
$password=$_POST['password'];
$username= htmlspecialchars($username);
$validForm = true;
if (empty($_POST["username"]))
{
$validForm=false;
}
if (empty($_POST["password"]))
{
$validForm=false;
}
if (!$validForm) {
$error = "please ensure all fields are filled in";
include("add.php");
return false;
}
$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{
header( "Location: search.php" );
}else{
$error = "The details you have entered are incorrect";
include("add.php");
}
$conn=NULL; //close the connection
Update
also tried this: Knowing this doesnt work, tested with echo statements but still no luck
function hash_input() {
$password = "sfafgsd";
return $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
}
function selectUser($conn, $username, $password)
{
$query = "SELECT password FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->execute();
echo $username . " " . $password;
if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "WE MADE IT";
if(password_verify(hash_input($password), $row['password'])){
$_SESSION['username'] = $username;
echo "Welcome, you are now logged in as " . $username;
return true;
}
//echo "Your details were not found";
sleep(1);
return false;
}
else
{
//echo "Your details were not found";
return false;
}
}
The comments given by Mark cover the below exactly.
Order of events:
Send username to database and collect the hashed password from the row found.
run the password string given through password_verify to compare with the hashed value
return this result (true/false).
Celebrate. Have a coffeee or a tea.
There is no need to $_SESSION password data and this is a bad idea. Password data (hash or plaintext) should not be retained beyond this function call. If you do for some reason need to have a nonce value associated with this account/membership/login then this should be setup using a random string in its own column in the database.
Improved Function Code
function selectUser($conn, $username, $password)
{
$query = "SELECT password FROM login WHERE username = :username LIMIT 1";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
// $stmt->bindValue(':password', $password); NO Don't do this.
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if(password_verify($password,$row['password'])){
$_SESSION['username'] = $username;
// $_SESSION['password'] = $password; DO NOT DO THIS
echo "Welcome, you are now logged in as " . $username;
return true;
}
//bad password
//echo "Your details were not found";
sleep(1); // it can be a good idea to add a forced pause on
// password fail to discourage brute force cracking.
return false;
}
//echo "Your details were not found";
return false;
}

Categories