Three "elses" in "if" statement - php

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 .

Related

PHP login form does not read user level

I want to make a login form which can be used by normal users and admins. The code should tell the difference between normal users and admins and based on it, start a new session after user is logged in (admin or user session). In my database table, I added "level" column which should determine if user is an admin or not (for ex.: if the user level is 3, then they are admin).
Here is my login.php file:
if (isset($_POST['submit'])) {
include_once 'database.php';
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username or !$password) {
header('Location: login.php');
} else {
$execution = "SELECT level FROM users WHERE name = '$username' AND password = '$password';";
$result = mysqli_query($database, $execution);
if (mysqli_num_rows($result) == 1) {
session_start();
$_SESSION['user'] = $username;
header('Location: login.php');
exit();
} elseif (mysqli_num_rows($result) == 3) {
session_start();
$_SESSION['admin'] = $username;
header('Location: index.php');
exit();
} else {
header('Location: login.php');
exit();
}
}
}
The code does not work because when I try to log in with a user that has LEVEL 3 in database, it still starts the normal user session and does not go through the elseif statement that I wrote above. How do I fix this? Maybe I am doing this completely wrong and there is another way to do this admin/user login thing?
Btw: I do understand that I'm storing passwords in plain text here, but right now I am only experimenting with the code and do not plan to upload it to a website.
Because you aren’t checking the user’s level at all.
Your first if block only checks if the result has one row.
Also, you should use prepared statements to prevent injection.
This is the correct code:
if (isset($_POST['submit'])) {
include_once 'database.php';
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username or !$password) {
header('Location: login.php');
} else {
$execution = mysqli_prepare($database, "SELECT level FROM users WHERE name = ? AND password = ?;";
mysqli_stmt_bind_param($execution, "ss", $username, $password);
mysqli_stmt_execute($execution);
$result = mysqli_stmt_get_result($execution);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
session_start();
if ($row['level'] == 1) {
$_SESSION['user'] = $username;
header('Location: login.php');
}
elseif ($row['level'] == 3) {
$_SESSION['admin'] = $username;
header('Location: index.php');
}
exit();
echo "$result";
} else {
header('Location: login.php');
exit();
}
}
}
Here is your code updated.
You need to get the value of level in order to apply the permissions.
session_start();
if ($result->num_rows > 0){
if($row['level'] == 1){
$_SESSION['user'] = $username;
header('Location: login.php');
exit();
}elseif( $row['level'] == 3){
$_SESSION['admin'] = $username;
header('Location: index.php');
exit();
}else{
header('Location: login.php');
exit();
}
}
Hope it helps.

Cookies not saving (PHP)

My cookies are not saving, I am using PHP 5.
Code:
require 'dbcon.php';
$sql = "SELECT * FROM accounts";
$result = $conn->query($sql);
$username = $_POST['username'];
$password = $_POST['password'];
$row = mysql_fetch_row($result);
setcookie("ID6", $row['ID'], time() + 60*60*24*31*12, "/") or die("Cookie could not be set. <a href='index.php'>Try again!</a>");
if(!isset($_POST['username']) || !isset($_POST['password'])) {
header("Location: index.php");
exit();
}
while($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) {
if($password == $row['password']) {
if($row['accdel'] == 1) {
echo("You are banned.");
exit();
}
echo "Logged in with cookie:" . $_COOKIE['ID6'];
exit();
}
else {
echo "The account does not exist, or you have put in the wrong log in.";
exit();
echo"That's not an account name though...";}
}
}
?>
Please help. Is the selected sql even a settable cookie value? (Please make it simple. I do not know much about php nor cookies.
https://www.jqueryscript.net/other/E-commerce-Cart-Plugin-For-jQuery.html
I tried save cookies with PHP many days never work.
Maybe try jquery.
The ID wasnt got from the database because it was not in the while loop.

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';
}
}

log in system with sessions and mysqli done something wrong

Hello guys I am trying to make a simple log-in system for a school project, I got it to work when I didn't implement the database. But as you can see now that I tried to implement the database it don't work so well since I can't make the PHP tags at the start and end of the echo's, anyway anyone who can help me out?
As I said it worked when I just wrote a random username and password, and didn't have any database thing on it.
<?php
session_start();
include('../inc/dbconnection_inc.php');
$result=mysqli_query($dbconnection, 'SELECT * FROM users');
$row=mysqli_fetch_array($result);
$p=$_POST['password'];
$u=$_POST['username'];
if ($u==echo $row["username"] AND $p==echo $row["password"]);
{
$_SESSION['username'] = echo $row["username"];
header("Location: admin.php");
}
else
{
header("Location: ../index.php");
}
I am not sure that you need echo there. According to the manual, echo returns nothing.
Try removing all echo's from the code, like
...
if ($u === $row["username"] && $p === $row["password"])
{
$_SESSION['username'] = $row["username"];
header("Location: admin.php");
}
(also I usually use && instead of AND, that also could be the cause)
Besides your code will check only first fetched row (I think you're aware of that?)
$p=$_POST['password'];
$u=$_POST['username'];
$query = 'SELECT * FROM users WHERE username = ?';
if($result=mysqli_query($dbconnection, $query)){
mysqli_stmt_bind_param($result, "s", $u);
mysqli_stmt_execute($result);
$row=mysqli_fetch_array($result);
if ($u == $row["username"] && $p == $row["password"]);
{
$_SESSION['username'] = echo $row["username"];
header("Location: admin.php");
}
else
{
header("Location: ../index.php");
}
}else{
//fail
}
Remove the echo
Select a specific user by adding a Where Clasuse
Prepare your statment

Outputting incorrect username or password

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.

Categories