Outputting incorrect username or password - php

I need help with this code to output incorrect username or password but it doesn't :(
<?php
include 'functions.php';
if(loggedin()){
header("Location: index.php");
exit();
}
if(isset($_POST['login'])){
$username=$_POST['Username'];
$password=$_POST['Password'];
if(isset($_POST['rememberme'])){
$rememberme = $_POST['rememberme'];
}
if($username&&$password){
$login = mysql_query("SELECT * FROM php_customer WHERE Username='$username'");
while($row = mysql_fetch_assoc($login)){
$db_password = $row['Password'];
if($password == $db_password){
$loginok= TRUE;
}
else{
$loginok= FALSE;
}
if($loginok==TRUE)
{
if($rememberme=="on"){
setcookie('Username',$username, time() + 7200);
}else if ($rememberme==""){
$_SESSION['Username'] = $username;}
header("Location: index.php");
exit();
}
echo "Incorrect Username or Password";
}
}
}
?>
I've tried adding it by the $loginok=false; but nothing works. I don't want you guys to go psycho on me, this is a 1 line of code kinda thing. Also yes I know you can log in if you store a username as a cookie. Just trying to validate atm.

Set your flag to false at the very beginning, before doing the SQL query:
$loginok = FALSE;
$login = mysql_query(....);
Why? Because the SQL query won't return anything for a username that doesn't exist in the table, obviously.
Which means, also, you need to make sure that the line echo "Incorrect Username or Password"; and the if-statement based on $loginok are not inside the loop which goes through the recordset, but after it. Which means you need to learn how to properly indent code so its clear where if-statements and loops begin and end.

Related

php user login script

<?php
if(isset($_POST['submit'])) {
$UserName = mysql_real_escape_string($_POST['UserName']);
$password = mysql_real_escape_string($_POST['password']);
$checkbox = isset($_POST['remember_me']);
if(user_exists ($UserName, $db_connect)) {
$result = mysqli_query ($db_connect, "SELECT password FROM users WHERE UserName = '$UserName'");
$retrievepassword = mysqli_fetch_assoc($result);
if(md5($password) !== $retrievepassword['password']) {
$alert = "Invalid Password";
} else {
$_SESSION['UserName'] = $UserName;
if($checkbox == "on") {
setcookie("UserName", $UserName, time()+3600);
}
header("location: profile.php");
}
} else {
$alert = "Username doesn't exit in database";
}
}
?>
I've made the following login script which is working fine and now I want to check the user's status before login, if user is active, it will login and if it's request is pending or rejected, it will display an error.
I've done the 1st part and confused about the other part where I've to check for the status.
Can anybody help me according to my code?
I am assuming that you have a column in your DB that stores the user's status.
Sooo .. The answer to your question is, after checking if the username is existing in you DB, check if the status is "active" or not. If no, then just display the error message.
You may think of another way to query your data, like:
SELECT * FROM USERS WHERE USERNAME = 'username' AND PASSWORD = 'password' AND STATUS = true
So that you can determine right away if it is active or not if it does not return anything.
I hope this helps. :)
You can check status after checking valid password and return appropriate message. Try below code :
if(user_exists ($UserName, $db_connect))
{
$result = mysqli_query ($db_connect, "SELECT password,status FROM users WHERE
name = '$UserName'");
$retrievepassword = mysqli_fetch_assoc($result);
if(md5($password) !== $retrievepassword['password'])
{
$alert = "Invalid Password";
}
else
{
//check Status
if($retrievepassword['status'] == 1) //whatever condtion to match
{
$_SESSION['UserName'] = $UserName;
if($checkbox == "on")
{
setcookie("UserName", $UserName, time()+3600);
}
header("location: profile.php");
}
else
{
$alert = "User Not active"; //Message to display
}
}
}
else
{
$alert = "Username doesn't exit in database";
}
There are two ways :
Either add condition in your where to check whether user is active
or not.
Or, once you validated user for correct user/password, then
validate through if condition and navigate to correct page
accordingly.
Also, correct your SQL to use prepared statement.
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE
UserName = ? AND password = ?');
$stmt->bind_param('s', $UserName);
$stmt->bind_param('s', md5($password));
$stmt->execute();
First of all, I would like to point out that you have used $ _SESSION without starting the session. To do this you have to write
session_start();
at the beginning of the code.
To verify that the user is logged in, write this just under session_start():
if(isset($_SESSION['UserName']) or isset($_COOKIE['UserName'])){
header("location: profile.php");
}
If you do not know how to check in profile.php if the user is logging in here is how to do it:
PS: I suggest you create a check.php file so that you just include it in the pages reserved for logged in users.
check.php
if(!isset($_SESSION['UserName']) or !isset($_COOKIE['UserName'])){
// Redirect to login or enter what you want to happen if the user is not logged in
}

login system only accepts access to first item in the database

The problem with my simple login system is that it only accepts access from the first item in the database, which is "user1". When I tried to login the second user, which is "user2", it says incorrect though the username and password combination was actually correct. Can someone help me figure out what's wrong with my code?
<?php
session_start();
$pdo = new PDO('mysql:host=127.0.0.1;dbname=sample', 'root', '');
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = $pdo->query("SELECT * FROM users");
while($row = $query->fetch(PDO::FETCH_OBJ)) {
if($username == $row->username && $password == $row->password) {
$_SESSION['username'] = $username;
header('Location: success.php');
exit();
} else {
die('Incorrect username and password combination');
}
}
}
if(isset($_SESSION['username'])) {
header('Location: success.php');
exit();
}
?>
Description
Actually the problem is in your Logic and which is of using die() and exit() function. Look at your code the first iteration of while will not match with your user2 and the code will die(). The die() function ends all the flow of code hence every time you set username to user2 and run you will get the same result. Try to use die() or exit() function after the While Loop so the code moves to next iteration if not match on the first iteration.
Explnation
Moreover apply username and password by using where clause in query it will provide more benefits to you.
It will Minimize your code
By this logic which you are using at the moment, if your USER data increases
it will increase your process time of LOGIN because it will first fetch all the rows from USER table then iterate over it un-till it finds the match against username.
But if you still want to continue with this approach you may use as following
Code
session_start();
$pdo = new PDO('mysql:host=127.0.0.1;dbname=sample', 'root', '');
if (isset($_SESSION['username'])) {
//if session is already set navigate to success.php
header('Location: success.php');
} else {
//else if session is not set
//authenticate the user first
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = $pdo->query("SELECT * FROM users");
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
if ($username == $row->username && $password == $row->password) {
$_SESSION['username'] = $username;
header('Location: success.php');
exit();
}
}
return 'Incorrect username and password combination';
} else {
return 'username and password required';
}
}

Three "elses" in "if" statement

Is it possible to have an if statement with three else parts?
My login script checks the username, password and captcha. If the user/pass or captcha is wrong, the site return with an error saying "username or password incorrect". But I also want it to give an error when there are blank fields (just one is sufficient to give the error). I thought I could just add a third else{ but Dreamweaver gives an error.
How can I achieve this?
<?php
$username=$_POST["username"];
$password=$_POST["password"];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$query = mysqli_query($con, "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'");
$result = mysqli_num_rows($query);
if($result===1){
session_start();
$_SESSION["username"] = $username;
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
header('location:admin.php');
exit();
}
else{
session_destroy();
die(header("location:lgin.php?codeFailed=true&reason=code&user=$username"));
exit();
}
}
else{
session_destroy();
die(header("location:lgin.php?loginFailed=true&reason=login"));
exit();
}
else{ //dreamweaver gives an error here
session_destroy();
die(header("location:lgin.php?blank=true&reason=blank"));
exit();
}
?>
There can be only one else per if statement. If you are nesting if statement .. you can have more else .. but still one else block per if statement. As I see it , you have two if conditions and three else blocks. That will not work .. you will need to remove one last dangling else.
Also it will improve your code readability if you indent it properly.
if ($result === 1) {
session_start();
$_SESSION["username"] = $username;
if (isset($_POST["captcha"]) && $_POST["captcha"] != "" && $_SESSION["code"] == $_POST["captcha"]) {
header('location:admin.php');
exit();
} else {
session_destroy();
header("location:lgin.php?codeFailed=true&reason=code&user=$username")
exit();
}
} else {
session_destroy();
header("location:lgin.php?loginFailed=true&reason=login")
exit();
}
You may want to use else if ... just in case you have more conditions to check. It will help if you visually draw a flowchart to see what you really want to achieve and then code it.
The code can be improved a lot .. but I guess that's not your primary concern here so I am leaving that .

How to set user/admin accounts for a redirect after log in? PHP

My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.

PHP not setting cookies but does set sessions

I have made a login that works for sessiosn but not cookies.. here is my login.php code
<?php
include 'functions.php';
if(loggedin()){
header("Location: index.php");
exit();
}
if(isset($_POST['login'])){
$username=$_POST['username'];
$password=$_POST['password'];
if(isset($_POST['rememberme'])) {
$rem=$_POST['rememberme'];
} else { $rememberme=""; }
if($username&&$password){
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
while($row = mysql_fetch_assoc($login)){
$db_password = $row['password'];
if($password == $db_password){
$loginok= TRUE;
}
else{
$loginok= FALSE;
}
if($loginok==TRUE)
{
if($rememberme=="on"){
setcookie("username",$username, time() + 7200);
}else if ($rememberme==""){
$_SESSION['username'] = $username;}
header("Location: index.php");
exit();
}
else
die("Incorrect Username/Password");
}
}
else
die("Please enter a username and password");
}
and my functions.php
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$db = "loginphp";
mysql_connect($host, $user, $pass) or die("Couldn't connect");
mysql_select_db($db);
function loggedin()
{
if(isset($_SESSION['username'])||(isset($_COOKIE['username'])))
{
$loggedin = TRUE;
return $loggedin;
}
}
but when I close the broswer the cookie does not save and it acts as if i've logged out completely.
sessions work fine..
here is my logout.php as well
session_start();
session_destroy();
setcookie("username","",time() - 7200);
header("Location: login.php");
I changed the format for your cookie to allow it to live for 30 days, no matter what you should always verify data in set duration of time. You assigned the $_POST to $rem not $rememberme so I corrected your function:
if($loginok==TRUE)
{
if($rem=="on"){
setcookie('username', $username, time() + (60 * 60 * 24 * 30)); // expires in 30 days
}else if ($rem==""){
$_SESSION['username'] = $username;}
header("Location: index.php");
exit();
}
I suggest you rethink how you are dealing with the remember me logins, perhaps you should come up with a hash that you can store in an encrypted format in the cookie and verify it on the server side. This "hash" should change at each visit etc.. just a recommendation.
function loggedin()
{
if(isset($_SESSION['username'])||(isset($_COOKIE['username'])))
{
$loggedin = TRUE;
return $loggedin;
}
It seems like you're setting $rem, rather then $rememberme. Change the line to:
$rememberme = $_POST['rememberme'];
Just to warn you though, with this method if someone wanted to log in, all they'd have to do is set a username in a cookie and bingo!
Have a look at the accepted answer here for a good method.
While I'm at it, you also need to protect yourself against SQL injection attacks, which your current code is open to. Look here.

Categories