If and else statement , test on the user account status - php

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

Related

How do I add Login Details confirmation if incorrect?

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']."')";
}
}
?>

Multiple User Type Login Through Single Login Page Issue

I am working on php and mysql code on making access to different pages based on the role of the user, through one Login Page.
Its working good for 'admin' page ..
but not able to login with 'normal type'
Little Help is really appreciated, Thank You
Here is my Code
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query) ;
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result) ;
if ($count == 1) {
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
}
elseif($row['user_type'] = 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
}
?>
Move your session code after if condition and then redirect. Also is there any specific reason to store password in session. == missing
Use proper filters for inputs.
if ($count == 1) {
if(!empty($row['user_type'])) {
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
//$_SESSION['password'] = $row['user_pass'];
}
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
}
elseif($row['user_type'] == 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
The logic test for the normal user was using a single = sign which sets a value rather than tests for equality - it needs to be ==
Also, I think the WRONG USERNAME OR PASSWORD wa at the wrong level - it needs to be the else to the record count
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result);
if ($count == 1) {
if($row['user_type'] == 'admin') {
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
/* require `==` here */
} elseif( $row['user_type'] == 'normal' ) {
header('Location: index.php');
} else {
die('unknown/unhandled user level');
}
/* changed location of this by one level */
} else {
echo "WRONG USERNAME OR PASSWORD";
}
}
?>
This is function for login.
It presumes password come from user with sha512 encryption (see js libs like https://github.com/emn178/js-sha512) - it's good for non-encrypted connections.
It uses salt, and have some protection from brute force, CSRF, XSS and SQL-injection.
static public function db_login($email, $p)
{
if ($stmt = Site::$db->prepare(
"SELECT id, password, salt, name
FROM user
JOIN contact ON contact_id = id
WHERE email = ?
LIMIT 1")
) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $db_password, $salt, $name);
$stmt->fetch();
// hash the password with the unique salt
$p = hash('sha512', $p . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (self::checkBrute($user_id) == true) {
// Account is locked
$res['code'] = 0;
$res['reason'] = 'trylimit';
$res['message'] = 'You try too many times. Come back on 30 minutes';
return $res;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $p) {
// Password is correct!
// Get the user-agent string of the user.
// CSRF
$user_browser = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_SPECIAL_CHARS);
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
Login::sec_session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = htmlspecialchars($email);
$_SESSION['name'] = htmlspecialchars($name);
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['login_string'] = hash('sha512', $p . $user_browser);
session_write_close();
// Login successful
$res['isLogined'] = 1;
$res['code'] = 1;
$res['name'] = $name;
$res['id'] = $user_id;
return $res;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
Site::$db->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
$res['code'] = 0;
$res['reason'] = 'pass';
$res['message'] = 'Wrong password';
return $res;
}
}
} else {
// No user exists.
$res['code'] = 0;
$res['reason'] = 'user';
$res['message'] = 'We have no such email';
return $res;
}
}
$res['code'] = 0;
$res['reason'] = 'SQL-error';
return $res;
}

Can't fetch data from MySQL (php) (Re-edited)

I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.

How to add a remember me function in login?

session_start();
if(isset($_POST['submit'])) {
$uname = $_POST['uname'];
$pw = $_POST['pw'];
require_once('db.php');
$sql = 'SELECT * FROM users_table
WHERE username="'.mysql_escape_string($uname).'" AND password="'.mysql_escape_string(md5($pw)).'"
LIMIT 0, 1
';
$qry = mysql_query($sql);
$count = mysql_num_rows($qry);
if($count > 0) {
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
header('Location: products_list.php');
} else {
header('Location: index.php?error=1');
}
}
use setcookie() function to set the cookie and then retrieve it when user acess the login restricted pages
setcookie description
I have done it using the Cookie, it runs amazingly perfect...
Only thing you need to do is just add encoding in cookies for security...
session_start();
if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['submit'])) {
$uname = $_POST['uname'];
$pw = $_POST['pw'];
require_once('db.php');
//Checking whether the cookies are set or not
if(!empty($_COOKIES['Last_Login_UserID']) && !empty($_COOKIES['Last_Login_Password'])){
if($_COOKIES['Last_Login_UserID']==$uname && $_COOKIES['Last_Login_Password']==$pw){
//Cookies are perfect give access
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
header('Location: products_list.php');
}else{
//Cookies cookies are wrong
login_check($uname,$pw);
}
}else{
//Cookies are not set so check the database
login_check($uname,$pw);
}
//Function to check the login
function login_check($uname,$pw){
$sql = 'SELECT * FROM users_table WHERE username="'.mysql_escape_string($uname).'" AND password="'.mysql_escape_string(md5($pw)).'" LIMIT 0, 1 ;';
$qry = mysql_query($sql);
$count = mysql_num_rows($qry);
if($count == 1) {
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
if(!empty($_POST['remember_me']) && $_POST['remember_me']==true){
setcookie('Last_Login_UserID',$_SESSION['username'],(60*60*24),"/");
setcookie('Last_Login_Password',$_SESSION['password'],(60*60*24),"/");
}
header('Location: products_list.php');
} else {
header('Location: index.php?error=1');
}
}}

Login suddenly stopped working

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).

Categories