I am new to php and mysql and I have began coding a simple social media network. So I am currently working on my login.php page which seem to have no errors, but it is not working as it should and I am assuming it is because the query is not being recognised as a statement. i.e "password" should not be highlighted as a key word but it is a field in the database. I am also aware that I have not considered injection. When I run this in the browser there are no errors but it returns "User not registered" even when a user is in the database. Any insight would be great thanks!
Here is my code:
<?php
include('classes/DB.php');
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username',
array(':username'=>$username))) {
if (password_verify($password, DB::query("SELECT password FROM
users WHERE username=:username", array(':username'=>$username))[0]
['password'])) {
echo 'Logged in!';
} else {
echo 'Incorrect Password!';
}
} else {
echo 'User not registered!';
}
}
Here is my DB.php class:
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=SocialNetwork;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
<?php
include('classes/DB.php');
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username',
array('username'=>$username))) {
if (password_verify($password, DB::query("SELECT password FROM
users WHERE username=:username", array('username'=>$username))[0]
['password'])) {
echo 'Logged in!';
} else {
echo 'Incorrect Password!';
}
} else {
echo 'User not registered!';
}
}
Related
so I have this site where drivers can login and register.
at the moment i can store the username in a session variable, im trying to do the same for the user_id so the user can later retrieve it when adding more details for a job.
heres what I got so far:
function selectUser($conn, $username, $password, $userID)
{
$query = "SELECT * FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
//$stmt->bindValue(':user_ID', $userID);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
if (md5($password) == $row->password) {
$_SESSION['username'] = $username;
$_SESSION['user_ID'] = $userID;
// $_SESSION['password'] = $password;
echo "Welcome, you are now logged in as " . $username;
return true;
}
return false;
}
else
{
//echo "Your details were not found";
return false;
}
}
when the driver accesses another page:
<?php
if(!isset($_SESSION))
{
session_start();
}
require_once ("config.inc.php");
try
{
$conn = new PDO(DB_DATA_SOURCE, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $exception)
{
echo "Oh no, there was a problem" . $exception->getMessage();
}
if(isset($_SESSION["username"]))
{
echo "Welcome, you are now logged in as <b>".$_SESSION['username']."</b> <img class='clientView' src='images/loginIcon.png' alt='client'>"; }
else {
echo "You are currently not logged in";
}
$login = $_SESSION['user_ID'];
$query = "SELECT * FROM login WHERE user_ID = :login";
$term = $conn->prepare($query);
$term->bindValue(':login', $login);
$term->execute();
$login = $term->fetch(PDO::FETCH_OBJ);
print_r($_SESSION);
?>
tested it using print r and for some reason it doesnt seem to be collecting the user_ID.
am i doing something wrong?
upon test: https://snag.gy/6bGd5m.jpg
when calling the function:
$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: profile.php');
}else{
$error = "The details you have entered are incorrect";
include("add.php");
}
Debug.
Where do you store the value in the session state?:
$_SESSION['user_ID'] = $userID;
Ok, so where does $userID come from?:
function selectUser($conn, $username, $password, $userID)
{
//...
Ok, so where does the function parameter come from?:
selectUser($conn,$username,$password)
Nowhere. You never supplied a value to be stored in session, so no value was stored in session.
It seems unlikely that you actually want to supply the User ID to the function. Instead, you probably want to supply just the username and password as you currently do and then get the User ID from the database. Which might look more like this:
$_SESSION['user_ID'] = $row["user_ID"];
Or perhaps:
$_SESSION['user_ID'] = $row->user_id;
Or however you get values from your $row object.
But basically the important lesson here is... When a value isn't what you expect it to be, trace back where that value came from. Chances are you have a false assumption somewhere.
I use
password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
for my signup form. It's okay in database save perfectly, but can't login.
This is my login function
public function Login($user, $password)
{
try {
$db = DB();
$query = $db->prepare("SELECT id FROM members WHERE user=:user AND password=:password");
$query->bindParam("user", $user, PDO::PARAM_STR);
$data = $this->query->single();
$getpass = $data['password'];
$passv = password_verify($password, $getpass);
$query->bindParam("password", $passv, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_OBJ);
return $result->id;
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
EDIT:
login.php
<?php
// Start Session
session_start();
// Database connection
require __DIR__ . '/database.php';
$db = DB();
// Application library
require __DIR__ . 'inc/functions.php';
$app = new DemoLib();
// check Login request
if (!empty($_POST['login'])) {
$user = trim($_POST['user']);
$password = trim($_POST['password']);
if ($user == "") {
echo 'Please enter username.';
} else if ($password == "") {
echo 'Please enter password.';
} else {
$id = $app->Login($user, $password); // check user login
if($id > 0)
{
$_SESSION['id'] = $id; // Set Session
}
else
{
echo 'Wrong data.';
}
}
}
?>
You don't want to try to match the password during the query as matching the hash would not work. In order to verify the password you will want to do something like this:
public function Login($user, $password)
{
try {
$db = DB();
$query = $db->prepare("SELECT * FROM members WHERE user=:user"); // get everything for the user
$query->bindParam("user", $user, PDO::PARAM_STR);
//$data = $this->query->single();
$data = $query->execute();
$getpass = $data['password'];
$passv = password_verify($password, $getpass);
if ($passv) { // if the password is good
return $data['id'];
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
No matter what I am doing I only get the password or username is incorrect string.What's going wrong?I had tried to run php's website example and it was working,so what am I doing wrong?
Here's the code guys:
<?php
include __DIR__.'/includes/database.php';
class Login{
public function validateCredentials($username, $password){
global $mysqli;
$query = "SELECT password FROM users WHERE username = '".mysqli_real_escape_string($mysqli,$username)."';";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_NUM);
if(password_verify($row['0'],$password)){return true;}
return false;
}
}
$object = new Login();
if(isset($_POST['username'])&&isset($_POST['password']))
{
if($object->validateCredentials($_POST['username'],$_POST['password']))
{
echo 'Logged in!';
}
else
{
echo 'Password or username incorrect!';
}
}
else
{
echo 'Username or password not entered!';
}
?>
Let's check for password_verify:
boolean password_verify ( string $password , string $hash )
See - first argument is password and second is hash.
In your code it's vice versa, you should use
if(password_verify($password, $row['0'])){return true;}
Try this...
<?php
include __DIR__.'/includes/database.php';
class Login{
public function validateCredentials($username, $password){
global $mysqli;
$query = "SELECT password FROM users WHERE username = '".mysqli_real_escape_string($mysqli,$username)."';";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_NUM);
return password_verify($password, $row['0']);
}
}
$object = new Login();
if(isset($_POST['username'])&&isset($_POST['password']))
{
if($object->validateCredentials($_POST['username'],$_POST['password']))
{
echo 'Logged in!';
}
else
{
echo 'Password or username incorrect!';
}
}
else
{
echo 'Username or password not entered!';
}
?>
I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.
I'm hashing a password using sha1 and it is successfully storing it in the database, however i cannot seem to properly check to see if the sha1 matches one that is in the database. I've tried numerous different iterations of the below code, but nothing seems to work - what am i missing?
Registration
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("INSERT INTO
user_info
SET
username = :user,
pass = :pass
");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
}
catch (Exception $e) {
echo "Could not create username";
}
if (isset($_POST['submit'])) {
foreach ($_POST as $field) {
if (empty($field)) {
$fail = true;
}
else {
$continue = false;
}
}
if ($field == $fail) {
echo "You must enter a username and/or password";
}
else {
echo "Your account has been successfully created.";
}
}
?>
Logging in
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$encryptedPassword = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
if ($rows) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
?>
You need to hash the password before querying the table, not afterwards:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
if ($result->fetch(PDO::FETCH_NUM)) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
?>