Why is my else condition being executed twice? - php

I went through this login system with multi-users. It's working fine since it doesn't allow my status_id users '2' to login (inactive status), but when this happens I get the echo message twice on screen.
What am I doing wrong?
I want to validate both user/password, user_type (admin/user) and user_status (1-active, 2-inactive).
<?php
include 'database/connect.php';
if (isset($_POST["submit"])) {
$email = $_POST["txtemail"];
$pass = $_POST["txtpass"];
$query = mysqli_query($con, "SELECT user_email,user_password,user_type_id, status_id FROM user");
while ($row = mysqli_fetch_array($query)) {
$db_email = $row["user_email"];
$db_pass = $row["user_password"];
$db_type = $row["user_type_id"];
$db_user_status = $row['status_id'];
if ($email == $db_email && $pass == $db_pass && $db_user_status == '1') {
session_start();
$_SESSION["email"] = $db_email;
$_SESSION["type"] = $db_type;
if ($_SESSION["type"] == '1') {
header("Location:admin/home_admin.php");
} else {
header("Location:user/home_user.php");
}
} else {
echo "Ups. Algo de errado aconteceu.";
}
}
}

Looking at your code, if the conditions specified inside the loop fails then the else will execute.
So if your user table holds 3 records and all 3 records doesn't satisfy the condition specified it will execute else statement and 3 times.
This might be the reason.

Well it looks like you are looping through every user inside your user table, so the posted email and password can only be right for one user and for the rest of them your program will go through the else statement

Related

Login count in php

I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.php');
}
}
?>
`

Trying to get property of non-object - PHP

So I'm trying to get the teacher_id that is corresponding to the teacher's first and last name that the user has entered, but when I try to get the teacher_id it outputs Trying to get property of non-object. Does anyone have any ideas?
PHP
<?php
// PROCESSES STUDENT INFO
// get connect page
require '../../connect.php';
// get input info
$student_id = $_POST['student_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$teacher_first_name = $_POST['teacher_first_name'];
$teacher_last_name = $_POST['teacher_last_name'];
// check if input is not empy
if(!empty($student_id) && !empty($first_name) && !empty($last_name) && !empty($teacher_first_name) && !empty($teacher_last_name)) {
// check if numeric inputs have a number
if(is_numeric($student_id)) {
$teacher_check = mysqli_query($link, "SELECT teacher_id FROM teachers WHERE first_name='$teacher_first_name' AND last_name='$teacher_last_name'");
// check if teacher exists
if($teacher_check) {
$row = $teacher_check->fetch_object();
$result = mysqli_query($link, "INSERT INTO students (student_id, first_name, last_name, teacher_id) VALUES ($student_id, '$first_name','$last_name', $row->teacher_id)");
if($result) {
header("Location: ../../../admin.php?message=Success!");
} else {
echo mysqli_error($link);
// header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=Teacher Does Not Exist");
}
} else {
header("Location: ../../../admin.php?message=Please add a number for Student ID");
}
} else if (empty($student_id) || empty($first_name) || empty($last_name)) {
header("Location: ../../../admin.php?message=Please add you're input values");
}
?>
change this line, you are checking whether the query is ok but you have not checked whether it has any results.
if($teacher_check) {
$row = $teacher_check->fetch_object();
to (this line checks whether you have any result data if you have result data you have it $row otherwise null)
if($row = $teacher_check->fetch_object()){

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

PHP/MySQL - Validating Usernames with Exceptions for Additional Characters

I've created an athletic league website with dynamic schedules and standings using PHP and MySQL. One of the basic functions of the website is for schools to select a game on the schedule that's already been played and log-in to report the score. You can see an example of the score reporting page below:
http://www.parochialathleticleague.org/report_score.html?league=test_league&game_id=5&away_team=St.%20Polycarp&home_team=St.%20Columban
After several months of work, everything seems to be working just right. However, I realized one important oversight this morning, just before the schedules for the new season are about to go live:
Some of our schools have multiple teams in each division because they have extra students. So, for example, there may be a St. Barbara AND a St. Barbara #2 participating in the same league and/or division. Sometimes, there are as many as three of four teams from the larger schools.
This is a problem because the validation code that I've written checks the school usernames to make sure they match the master school user accounts in the MySQL database before being allowed to report a score. Therefore, St. Barbara would not be authorized to report a score for their St. Barbara #2 team, even though they belong to the same school! I don't want to create separate user accounts for every team belonging to that school, so I need to modify the code in some way. I would like St. Barbara to be able to log-in with the same username for all of their different teams, regardless of whether or not there are additional characters at the end (if that makes sense).
Here's the function from my script that validates the username (school) to make sure they're one of the two teams participating in the game in question:
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} elseif ($_POST['school'] != $_POST['away_team'] && $_POST['school'] != $_POST['home_team']) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
Next, here's the function that later validates that the username and password match one of the records in the database:
// If all conditions are met, process the form:
if ($validate != 'false') {
$q1 = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass='$pass')";
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// ***a whole bunch of other stuff that I'm omitting because it's not relevant
}
}
Is there anyway to add an "addendum", so to speak, to the code that would make an exception for schools that have multiple teams? Sort of like:
elseif ($_POST['school'] == $_POST['away_team'] **MINUS ADDITIONAL INTEGERS AT THE END** || $_POST['school'] == $_POST['home_team'] **MINUS ADDITIONAL INTEGERS AT THE END**) {
$validate = 'true';
}
Sorry for the whole long spiel. Just wanted to make sure I explained it properly! Any thoughts? Your feedback is much appreciated.
EDIT - Here's the entire script for those that were interested:
<?php
// Connect to the database:
require ('../mysqli_connect.php');
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} elseif ($_POST['school'] != $_POST['away_team'] && $_POST['school'] != $_POST['home_team']) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the away score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the away score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['away_score'])) {
echo "You entered an invalid score for the away team.<br>";
$validate = 'false';
} else {
$away_score_confirm = mysqli_real_escape_string($db, trim($_POST['away_score']));
$validate = 'true';
}
// Validate the home score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the home score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['$home_score']) && $_POST['$home_score'] < 0 ) {
echo "You entered an invalid score for the home team.<br>";
$validate = 'false';
} else {
$home_score_confirm = mysqli_real_escape_string($db, trim($_POST['home_score']));
$validate = 'true';
}
// Determine the winner and loser, and set variables:
if ($_POST['away_score'] > $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['away_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['home_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$tie = 'no';
} else if ($_POST['away_score'] < $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['home_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['away_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$tie = 'no';
} else if ($_POST['away_score'] == $_POST['home_score']) {
$tie = 'yes';
$tie1 = mysqli_real_escape_string($db, trim($_POST['away_team']));
$tie2 = mysqli_real_escape_string($db, trim($_POST['home_team']));
$tie_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
}
// Declare remaining hidden inputs as variables:
$league = mysqli_real_escape_string($db, $_POST['league']);
$game_id = mysqli_real_escape_string($db, $_POST['game_id']);
// If all conditions are met, process the form:
if ($validate != 'false') {
$q1 = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass='$pass')";
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// Get the game ID:
$q2 = "SELECT $game_id FROM $league";
$r2 = mysqli_query($db, $q2);
// Get the row for the game ID:
$row = mysqli_fetch_array($r2, MYSQLI_NUM);
// Perform an UPDATE query to modify the game scores:
$q3 = "UPDATE $league SET home_score='$home_score_confirm', away_score='$away_score_confirm' WHERE game_id=$row[0]";
$r3 = mysqli_query($db, $q3);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
// Update the winning team in the standings:
$q4 = "SELECT school_id FROM test_league_standings WHERE school_name='$winner'";
$r4 = mysqli_query($db, $q4);
// Get the row for the school:
$row2 = mysqli_fetch_array($r4, MYSQLI_NUM);
$q5 = "UPDATE test_league_standings SET games=games + 1, win=win + 1, pts_for=pts_for + '$winner_score', pts_against=pts_against + '$loser_score' WHERE school_id=$row2[0]";
$r5 = mysqli_query($db, $q5);
$q6 = "UPDATE test_league_standings SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row2[0]";
$r6 = mysqli_query($db, $q6);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
// Update the losing team in the standings:
$q7 = "SELECT school_id FROM test_league_standings WHERE school_name='$loser'";
$r7 = mysqli_query($db, $q7);
// Get the row for the school:
$row3 = mysqli_fetch_array($r7, MYSQLI_NUM);
$q8 = "UPDATE test_league_standings SET games=games + 1, loss=loss+1, pts_for=pts_for + '$loser_score', pts_against=pts_against + '$winner_score' WHERE school_id=$row3[0]";
$r8 = mysqli_query($db, $q8);
$q9 = "UPDATE test_league_standings SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row3[0]";
$r9 = mysqli_query($db, $q9);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
if ($confirm != 'false') {
header("Location: schedules_test.html?league=" . $league);
} else {
echo "The scores could not be reported due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
} else {
echo "Your school and password combination do not match those on file for this game.";
}
}
mysqli_close($db);
?>
For the moment I'm going to assume that you're validating that $_POST['away_team'] and $_POST['home_team'] are valid and correct.
If you just want to check that $_POST['away_team'] begins with the string $_POST['school'], you can use the strpos function:
elseif (strpos($_POST['away_team'], $_POST['school']) === 0 || strpos($_POST['home_team'], $_POST['school'])) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
}
I'd like to assent to tadman's comment about SQL injection. Even if you aren't willing to rewrite your application to take advantage of the superior methods of injecting data into queries, you absolutely should escape your data when you run your query. Do not escape it anywhere else. If you do, eventually you will forget to escape it and it won't be as obvious as it should be. For example:
if ($validate != 'false') {
$q1 = sprintf(
"SELECT school_id FROM user_schools WHERE (school_name='%s' AND pass='%s')",
mysqli_real_escape_string($_POST['school']),
mysqli_real_escape_string($_POST['pass'])
);
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// ***a whole bunch of other stuff that I'm omitting because it's not relevant
}
}

PHP script doesn't enter ELSE clause on IF statement (login test)

I'm stumped on this one. Very simple login screen. When there is a password match the script works perfectly and jumps to main.php. When the uname or pswd is wrong, the script wont drop into the ELSE clause and wont go to badlogin.php. The script just hangs with the blank white screen.
any help would be great.
<?php
include("dbconnect.php");
$u_name = mysql_real_escape_string($_POST['uname']);
$p_word = mysql_real_escape_string($_POST['pword']);
# *** querying all records ***
$query = mysql_query("SELECT * FROM notes_users WHERE valid_password = '$p_word' && valid_username = '$u_name'");
while($rst = mysql_fetch_array($query)) {
if (($rst[valid_username] == $u_name) AND ($rst[valid_password] == $p_word)) {
session_start();
$_SESSION['login'] = "1";
header('Location: main.php') ;
} else {
session_start();
$_SESSION['login'] = '';
header('Location: badlogin.php') ;
}
}
?>
If there's no results returned from the query then "while($rst = mysql_fetch_array($query))" will never prove true, and the while loop is skipped over entirely.
edit: You could change it to a "do while" or just fix your while conditional.
You should have quotes around valid_username and valid_password. Right now, you are using them as constants. And you don't need the loop and if to check if the pair matches, you're already checking that on your query. I think your problem may be that you are comparing the values from the db with escaped values when you do that second comparison. Wiseguy and VDH are right, you never enter the while when the query returns false. Anyway, this simpler version should address all these issues:
<?php
session_start();
include("dbconnect.php");
$u_name = mysql_real_escape_string($_POST['uname']);
$p_word = mysql_real_escape_string($_POST['pword']);
# *** querying all records ***
$query = mysql_query("SELECT * FROM notes_users WHERE valid_password = '$p_word' AND valid_username = '$u_name'");
if(mysql_num_rows($query) > 0) {
    $_SESSION['login'] = "1";
    header('Location: main.php') ;
} else {
    $_SESSION['login'] = '';
    header('Location: badlogin.php') ;
}
?>
Here are some changes, you should not loop through the result if your only expecting a match:
<?php
//Session start at the top
session_start();
include("dbconnect.php");
$u_name = mysql_real_escape_string($_POST['uname']);
$p_word = mysql_real_escape_string($_POST['pword']);
# *** querying all records ***
//Some changes, use a LIMIT clause unless your expecting multiple users
//And as your only checking for row existence there no need to return *
//And never have plain txt passwords in db, use at least sha1 and not md5
$query = mysql_query('SELECT 1
FROM notes_users
WHERE valid_password ="'.sha1($p_word).'" && valid_username = '.$u_name.'" LIMIT 1');
//assoc
$rst = mysql_fetch_assoc($query);
//User found
if(mysql_num_rows($rst)==1){
$_SESSION['login'] = true;
header('Location: ./main.php');
die;
}else{
//User not found
$_SESSION['login'] = false;
header('Location: ./badlogin.php');
die;
}
?>

Categories