I have this form and start by checking if the fields are empty and it works pretty well. My question here is: why do i get errors when I want to verify if user exists?
Here is my code:
<?php
require_once '../../includes/database.php';
require '../../includes/functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$repassword = $_POST['re-password'];
$conn = connect($config);
if(empty($username) || empty($password) || empty($repassword)) {
$status = 'Fields must not be empty';
}
$results = $conn->query("SELECT * FROM admin WHERE username = " . $username);
foreach($results as $result) {
print_r($result);
}
}
include 'staff_create.view.php';
You need to enclose username between ' because is a string.
But you should use the potential of prepared statements:
$stmt = $conn->prepare("SELECT * FROM admin WHERE username = ?");
$stmt->execute($username);
$stmt = $stmt->fetchAll(PDO::FETCH_CLASS);
Or
$stmt = $conn->prepare("SELECT * FROM admin WHERE username = :username");
$stmt->execute(array(":username" => $username));
$stmt = $stmt->fetchAll(PDO::FETCH_CLASS);
You will avoid SQL injection writing your querys this way
You also might to check to see if the username is set...
$username="";
if (isset($_POST['username'])) {
$username = $_POST['username'];
}
You are missing the else statement and maybe a hard error after the $status is set...
<?php
require_once '../../includes/database.php';
require '../../includes/functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$repassword = $_POST['re-password'];
$conn = connect($config);
if(empty($username) || empty($password) || empty($repassword)) {
$status = 'Fields must not be empty';
}
else {
$results = $conn->query("SELECT * FROM admin WHERE username = " . $username);
foreach($results as $result) {
print_r($result);
}
}
}
include 'staff_create.view.php';
Related
How do I add Login Details confirmation if incorrect? what I want to happen is when the user puts his/her credentials their userID and Password are correct but the user type is wrong if the user presses the login button it will say "incorrect credentials" and same goes with userID and Password if they input the wrong credentials
<?php
include "includes/config.php";
session_start();
if(isset($_POST['loginbutton'])){
$username = $_POST['username'];
$password = $_POST['password'];
$usertype = $_POST['usertype'];
if ($username != "" && $password != ""){
$sql_query = "SELECT * FROM tbl_useraccounts WHERE employee_id='".$username."' and password='".$password."' and usertype='".$usertype."'";
$result = mysqli_query($con,$sql_query);
while ($row=mysqli_fetch_array($result)) {
if ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='Admin'){
$_SESSION['username'] = $_POST['username'];
header('location: home.php');
}
elseif ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='SuperAdmin') {
$_SESSION['username'] = $_POST['username'];
header('location: HomeForSuperAdmin.php');
}
}
}
}
?>
Dharma Is correct!
You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries!
If you embed a string in some SQL targeting MySQL, you must escape the string with MySQL's function for this purpose (mysqli_real_escape_string) and trigger db query to input on failed login.
Modified code:
<?php
include "includes/config.php";
session_start();
if(isset($_POST['loginbutton'])){
$username = $_POST['username'];
$password = $_POST['password'];
$usertype = $_POST['usertype'];
$loginFlag = true;
if ($username != "" && $password != ""){
$sql_query = "SELECT * FROM tbl_useraccounts WHERE employee_id='".$username."' and password='".$password."' and usertype='".$usertype."'";
$result = mysqli_query($con,$sql_query);
while ($row=mysqli_fetch_array($result)) {
if ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='Admin'){
$_SESSION['username'] = $_POST['username'];
header('location: home.php');
$loginFlag = true;
}
elseif ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='SuperAdmin') {
$_SESSION['username'] = $_POST['username'];
header('location: HomeForSuperAdmin.php');
$loginFlag = true;
}
else {
$loginFlag = false;
}
}
}
if($loginFlag == false){
#real_escape_string is used to prevent sql injection
$username = real_escape_string($_POST['username']);
$password = real_escape_string($_POST['password']);
$usertype = real_escape_string($_POST['usertype']);
# query assume table name log
$sql_query = "INSERT INTO log (username, password, usertype, ip_address)
VALUES ('$username ', '$password ', '$usertype ', '".$_SERVER['REMOTE_ADDR']."')";
}
}
?>
I want to make test on the status of the user account.
If the account is active I redirect him to the user page
If the account is not active I redirect him to login page again with an error
Here’s my code
<?php
require('conexion.php');
$username = '';
$password = '';
if (isset($_POST['username']) || !empty($_POST['username']))
$username = $_POST['username'];
if (isset($_POST['password']) || !empty($_POST['password']))
$password = $_POST['password'];
$q1 = "select * from user where username='" . $username . "' and password='" . $password . "' ";
$r1 = $db->query($q1);
$i = 0;
echo $q1;
while ($d1 = $r1->fetch()) {
$i++;
//$id_perso = $d1['id_perso'];
$type = $d1['type'];
$nom = $d1['nom'];
$prenom = $d1['prenom'];
$statut = $d1['statut'];
$user_id = $d1['id_user'];
}
if ($i == 1) { // START IF
session_start ();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if ($statut = 'actif') {
if ($_SESSION['type'] == 'admin') {
$path = "admin/index.php";
}
if ($_SESSION['type'] == 'professeur') {
$path = "professeur/index.php";
}
if ($_SESSION['type'] == 'doctorant') {
$path = "doctorant/index.php";
}
header("Location:".$path);
} elseif ($statut = 'inactif') {
header("location:login.php?inactif");
}
} else {
header("location:login.php?error=1");
}
?>
Why don't you use a boolean, should be easier.
/*
1. Get Status from Database
2. When the user is active, you set the boolean true, else false. */
$booleanVar = false;
if($booleanVar) {
// user is active
} else {
// user is inactive
}
EDIT:
Redirecting with header works like this, I believe its Case Insensitive:
header('Location: somesite.php?abc');
Also you have to check values with "==" (for equal) or "===" (for identical)
You could simply get the same result if you do this with a simple query:
You check if the password and the username matches AND check if the account has been activated.
$sql = 'SELECT `id` FROM `user` WHERE `username` = '$username' AND `password` = '$password' AND `statut` = 1'
You then can run the query and check if number of rows is greater than 0.
$sql = $db->query($sql);
$results = $sql->fetch();
if (count($results) > 0) {
// Account is activated
} else {
header("location: login.php");
exit;
}
You are also vulnerable to SQL-injections by inserting your variables directly into your query, wich Edhurtig noticed! The best way to prevend SQL-injections is to use PDO prepared statements.
First and foremost: DO NOT STORE PASSWORDS IN PLAINTEXT. Do some research into secure hashing algorithms (not md5) or use a third party authentication service like Google, Facebook, Github, ect.
Second: This code is vulnerable to SQL injection via $_POST['username'] and $_POST['password']
Also it was a bit unclear what was being asked but I felt it was important to point out the aforementioned issues because they are so security critical.
Here is what I was able to cleanup. I would strongly recommend using a third party authentication service though
<?php
require('conexion.php');
$salt = "random_string";
$username='';
$password='';
if (isset($_POST['username'])||!empty($_POST['username'])) $username = $_POST['username'];
if (isset($_POST['password'])||!empty($_POST['password'])) $password = $_POST['password'];
$hashed_password = some_hashing_function_1000_times($password, $salt);
$q1="SELECT * FROM user WHERE `user`.`username` = '%s' AND `user`.`password` = '%s' LIMIT 1";
// I hope that $db has a prepare function, it prevents SQL injections from $_POST['username'] and $_POST['password']
$sql = $db->prepare($q1, $username, $hashed_password);
$r1= $db->query($q1);
$user = $r1->fetch();
if( $user ) { // START IF
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if($statut == 'actif'){
if($_SESSION['type']=='admin') { $path="admin/index.php"; }
if($_SESSION['type']=='professeur'){ $path="professeur/index.php"; }
if($_SESSION['type']=='doctorant') { $path="doctorant/index.php"; }
header("Location: " . $path);
exit();
}
else if ($statut == 'inactif') {
header("Location: login.php?inactif");
exit();
}
}
header("Location: login.php?error=1");
exit();
// No Closing PHP tag at end of file
during registration, the user's password is saved in the database as an encrypted BCRYPT password.
My question is: Why can't I verify the encrypted database password with the entered password?
CODE:
<?php //POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
//PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
//CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$veri_password' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
//ERRS ARRAY DECLARED
$errors = array();
//FURTHER VERIFYING
if( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
while($row = mysql_fetch_array($entered_user)){
$_SESSION['key'] === true;
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
?>
I'm receiving an error that says 'account does not exist' even when I enter valid information.
Thanks,
-Eugene
EDIT CHANGED TO THIS:
<?php //POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
//PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
if($veri_password === true){
//CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$user_pass' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
//ERRS ARRAY ESTABLISHED
$errors = array();
//FURTHER VERIFYING
if( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
while($row = mysql_fetch_array($entered_user)){
$_SESSION['key'] === true;
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
}
?>
change to:
$sql = "SELECT id, username FROM users WHERE email='$email'";
Also change:
$veri_password = password_verify($password, $user_pass);
to
if(!password_verify($password, $user_pass)){
echo 'invalid password';
exit;
}
anyway, your code is vulnerable to sql injection. please consider using prepared statements in your queries or escape input strings with mysql_real_escape_string. . And also it is recommended to use mysqli or pdo instead of procedural methods
I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).
i tried to put username & password dynamically but
It doesnt work with stored username & password in DB and stays on same page....
really depressed.
<?php include "../db/db_connection.php";
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
if($_REQUEST['txt_username'] == $username && $_REQUEST['txt_pwd'] == $pwd){
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
header("Location:dashboard.php");
}
else{
header("Location:index.php");
}
?>`
Those lines doesn't nothing..
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
maybe:
$_SESSION['txt_username'] = $user;
$_SESSION['txt_pwd'] = ...;
?
You can try this, I am not sure if this is exactly what you are looking for...
<?php session_start();
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
header("Location:index.php"); // if it stays on the same page remove this line
?>
I restructured your code to look more clean.
Also I suggest you to avoid using mysql and start using mysqli (or PDO) to avoid SQL injection attacks.
<?php session_start();
if(isset($_SESSION['txt_username']) && !empty($_SESSION['txt_username'])) {
//If we enter here the user has already logged in
header("Location:dashboard.php");
exit;
}
if(!isset($_POST['txt_username'])) {
header("location:index.php?err_msg=1");
exit;
}
else if(!isset($_POST["txt_pwd"])) {
header("location:index.php?err_msg=2");
exit;
}
$username = $_POST['txt_username'];
$pwd = $_POST["txt_pwd"];
//We use MYSQL with prepared statements BECAUSE MYSQL IS DEPRECATED
$mysqli = new mysqli('localhost', 'my_bd_user', 'mi_bd_password', 'my_bd');
$sql = "SELECT 1 FROM users WHERE username= ? and password = ?";
$stmt = $mysql->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if(!empty($result)) {
//IF we enter here user exists with that username and password
$_SESSION['txt_username'] = $username;
header("location:dashboard.php");
exit;
}
else{
header("location:index.php?err_msg=3");
}
Try it.
I checked your code and found everything is correct .I wold like you to add connection file on this.
Like
$username = "root";
$password = "password";//your db password
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("db name",$dbhandle)
or die("Could not select Database");
Thanks
Try below code :
i have reviewed and changed your code :
<?php session_start();
mysqli_connect("locahost","username","password");
mysqli_select_db("database_name");
$username = trim($_POST['txt_username']);
$pwd = trim($_POST["txt_pwd"]);
if($username == ''){
header("location:index.php?err_msg=1");
exit;
}
if($pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT `username`,`password` FROM users WHERE `username`= '".$username."' and password= '".$pwd."'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result)>0){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
?>