I have written PHP code with many nested if conditions. I just want to display an alert for an exceptional condition along with the if conditions.
Here is my source code:
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
$query ="SELECT * FROM user where username='.$username.' AND pass='.$password.'";
$row = mysql_fetch_array($query);
$counted = mysql_num_rows($query);
if (($counted === 1) &&
($row['username'] === $username) &&
($row['password'] === $password))
{
session_destroy();
session_start();
echo "message";
} else {
do_alert("Exceptional alert");
}
} else {
do_alert("Exceptional alert");
}
These two else conditions are not working. I don't know really where my mistake is.
I think it may have to do with your do_alert down in your code. Follow me through the code.
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) { // if not empty
$query =""; // this is an empty query
$row = mysql_fetch_array($query); // returns nada
$counted = mysql_num_rows($query); // gives nada back
if (($counted === 1) && ($row['username'] === $username) && ($row['password'] === $password)) { // completely useless at this point cause no row is returned
session_destroy();
session_start();
echo "message";
} else { // this will not be executed
do_alert("Exceptional alert");
}
} else { // this will be executed
do_alert("Exceptional alert"); // where is this function defined?
}
okay i commented on your code where it goes wrong. As you see it happens already on the first if, so it should return the last else. Since I dont know where your do_alert code is defined, my guess is that this is your error.
Try replacing it first with an echo like this: echo "I am a super duper evil monkey"; and see if that works.
edit
since you added your query now, i 'd like to point out as well that you should sanitize your input. This to make it more safe. However the term safe here is kind of irralevant, cause you re using an outdated mysql set. (mysqli / pdo are the ways to go now)
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
why? simple. Look at this!
$_POST['username'] = 'awesome';
$_POST['password'] = "' OR ''='";
it would turn up something then like this.
SELECT * FROM users WHERE user='awesome' AND password='' OR ''=''
And this would mean, everybody could log in, cause blank is always blank. Just as a headsup.
More information here: http://php.net/manual/en/function.mysql-real-escape-string.php
edit 2
// very first thing you do if you work with sessions, is actually starting it. you dont do this in your if else statement, cause you could not benefit of the session variable on a later stage on this page.
session_start();
// these variables come from a form with a form name, so we are going to do a check if indeed this came from that form.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (!empty($username) &&
!empty($password)) {
$query ="SELECT name, password FROM user WHERE name='".$username."' AND password = '".$password."'";
$row = mysql_fetch_array($query);
$counted = mysql_num_rows($query);
if (($counted === 1) &&
($row['username'] === $username) &&
($row['password'] === $password)) {
echo "message";
} else {
echo "no entrees found";
}
} else {
echo "failed to input some variable";
}
I cleaned some up in my own words, you may have to fiddle with the query, and further i fixed it a bit since you didnt use the session appropiately.
Now where it echo's the message, you should set a session variable, that you can destroy later when you log out. A session variable you can call in the session itself, on every page that has sessionstart() in it. Here you can check if it excists, if so then you are logged in. I hope this helps you out.
Related
i'm making a login system linked with a database, i want to show an html file after the data get checked from the database.so, i used (the include method) an it shows me the html file in the console not on web page.
i've tried to use (require method) and tried to change it to php file and still doing the same.
<?php
$dbsevername = "127.0.0.1";
$dbusername = "root";
$dbpassword = "**************";
$dbname = "loginsystem";
$dbport = '3306';
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION["favcolor"] = "green";
$conn = mysqli_connect($dbsevername, $dbusername, $dbpassword,$dbname);
$sql = "SELECT * FROM passwords where username='$username' and password='$password';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result); // = 2
if ($resultCheck > 0) {
while($row = mysqli_fetch_assoc($result)){
if ($row['username'] == $username && $row['password'] == $password) {
include("true.html");
}
}
}else {
include("false.html");
}
mysqli_close($conn);
?>
i want to open the (true.php) or (false.php) when the data get checked.
I would rename to HTML files to PHP.
Is this actually your code? Just checking because if the files are a remote URL this makes a difference.
You are using a while loop to include a HTML file that will only ever have 1 result. There are better methods of doing this but regardless this should work and isn't the issue here. Any errors?
Try
include './true.php';
instead of
include ("true.html");
i want to open the (true.php) or (false.php) when the data get checked.
I think you are making a common rookie oversight here, because at the moment you only check if the data is correct and don't handle anything else:
I've commented through your code below to demonstrate what I mean
//if there is at least 1 result then check the data otherwise include false
if ($resultCheck > 0) {
//while we go through the results check each one
while($row = mysqli_fetch_assoc($result)){
//if the username and password match include true.html
//however you don't break out of the loop, you keep checking
//if you have decided to include true you should use break;
if ($row['username'] == $username && $row['password'] == $password) {
include("true.html");
}
//otherwise do what? this should say else include false and then should probably break out the loop here as the
//this will not fall through into the else block below as that is based on the parent condition
//so you will never include a false in this loop - only if there were 0 rows to begin with
//this means that eventually, whenever our loop finishes we will skip
//down to the next executionable line which is marked with !!!
}
}else {
include("false.html");
}
//!!!
there are some other glaring problems with your code, such as you seem to be storing passwords in pain text in your database, these should be hashed and verified, so you should never be able to just see if a password row == an input, i suggest googling php functions password_hash and password_verify
You also shouldn't be using a while loop, within your login system you must have a unique username and password combination so you should only ever return 1 row - if you have more than 1 row how can you confirm who they are? So you should be using whatever the mysqli equivalent of pdo->fetch() is (i don't know offhand because i only use pdo)
which brings me on to the fact that you should be using prepared statements to combat sql injection, at the moment this login system could be easily used to give someone full access to all your usernames and passwords, which are all stored in plain text.
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
if ($uid == null){
header("Location: ../index.php?message=ERROR 001 - Username or Password can not be
blank!");
exit();
}
if ($pwd == null){
header("Location: ../index.php?message=ERROR 001 - Username or Password can not
be blank!");
exit();
}
if ($stmt = $link->prepare("SELECT password FROM users WHERE username=?")) {
$stmt->bind_param("s", $uid);
$stmt->execute();
$stmt->bind_result($pass);
$stmt->fetch();
$stmt->close();
}
if (!$stmt) {
header("Location: ../index.php?message=ERROR 003 - Connection to the database could
not be established!");
exit();
}
$hash_pwd = $pass;
if ($hash_pwd == crypt($pwd, $hash_pwd)){
$decrypt = 1;
}else{
$decrypt = 0;
}
if ($decrypt == 0){
include ("false.html");
exit();
} else {
$stmt = $link->prepare("SELECT id FROM users WHERE username='$uid' AND password=?");
$stmt->bind_param("s", $hash_pwd);
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$stmt->close();
$_SESSION['id'] = $id;
include ("true.html");
}
This should work better. You'll have to change your database relevant details. I've given you a start with storing a session variable of ID.
Do I correctly do it? using header("Location: ....") to redirect to another page?
Could you suggest to improve may code because I'm new to this things..
<?php
require 'db.php';
$msg='';
if(!empty($_POST['username']) && isset($_POST['username']) && !empty($_POST['password']) && isset($_POST['password']))
{
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$sql = mysqli_query($connection, "SELECT username FROM admin WHERE username = '".$username."' AND password ='".$password."'");
$count = mysqli_num_rows($sql);
if($count == 1)
{
header("Location: AdminDeleteAccount.php");
exit;
}
else
{
$msg='Username and Password didnt match';
}
mysqli_close($connection);
}
else
{
echo 'howdie';
}
?>
yes you are doing it correctly, store the password in database using some kind of encrytption like MD5, sh1 etc. Also make sure that nothing is echoed out before the header function or else the header function will not work and you will see an error message.
I'm performing a query to check if a user exists before adding it to the database. If that result comes back then die and echo 'username already exists' but if it comes back empty then add the new user to the database.
For some reason it just adds a new user to the database anyway.
//If post was
if (isset($_POST['submit'])) {
// Check if username is blank
if (!isset($_POST['username']) || empty($_POST['username'])) {
echo "Username was blank<br />";
die();
} else {
$username = mysqli_real_escape_string($connection, $_POST['username']);
}
// Check if password is blank
if (!isset($_POST['password']) || empty($_POST['password'])) {
echo "Password was blank<br />";
die();
} else {
$password = mysqli_real_escape_string($connection, $_POST['password']);
$password2 = md5($password);
//echo $password;
}
// Check if email is blank
if (!isset($_POST['email']) || empty($_POST['email'])) {
echo "Email was blank<br />";
die();
} else {
$email = mysqli_real_escape_string($connection, $_POST['email']);
//$password = md5($password);
//echo $password;
}
//Check to see if username alread exsists
$query_check = "SELECT * FROM users WHERE user = '$username' LIMIT 1";
$result_check = mysqli_query($connection, $query_check);
if(count(mysqli_fetch_array($result_check)) === 1) {
echo "Username exists.";
die();
} else {
$query = "INSERT INTO users (user, pass, email) VALUES ('$username','$password2','$email');";
$result = mysqli_query($connection, $query);
if($result){ // returned TRUE, e.g. in case of a DELETE sql
$_SESSION["username"] = $username;
header("Location: ../profile.php");
} else { // returned FALSE
//echo "Error: " . mysqli_error($connection);
echo "Error during register <a href='../register.php'>Back To Register</a>";
die();
}
}
} else {
header("Location: ../index.php");
}
After taking a few minutes testing your code, found that you're using the wrong function.
mysqli_fetch_array():
Fetch a result row as an associative, a numeric array, or both
You're trying to fetch an associative array.
As opposed to mysqli_num_rows():
Gets the number of rows in a result
Replace (and which seems to have been taken from FĂ©lix's answer)
if(count(mysqli_fetch_array($result_check)) === 1)
with
if(mysqli_num_rows($result_check) == 1)
or
if(mysqli_num_rows($result_check) > 0)
Your original post contained:
if(mysqli_fetch_array($result_check) === 1)
which still stands to be the wrong method.
I even said to use mysqli_num_rows() in a comment, but nothing was said about it:
if(mysqli_num_rows($result_check) >0) and make sure $username is defined. We don't know how/where if it is even defined.
Now, if THAT fails, then your form element isn't named, and/or something else in your form is failing you.
I.e.: <input type="text" name="username">
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Regarding using MD5.
That isn't considered safe to use anymore, as far as password hashing goes.
That technology is old and is considered broken.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Pulled from ircmaxell's answer which uses PDO with prepared statements and password_hash():
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
Footnotes:
I noticed you are using headers.
You should add exit; after each header. Otherwise, your code may want to continue executing.
header("Location: ../profile.php");
exit;
and do the same for the other one also.
You're also using sessions. session_start(); isn't present in your posted and will fail if it isn't included; an insight.
here
if(mysqli_fetch_array($result_check) === 1) {
the value returned by mysqli_fetch_array won't be an integer but an array. You seem to want to count it:
if(count(mysqli_fetch_array($result_check)) === 1) {
In the case somehow two users would have been inserted for whatever reason, checking if count is greater than 0 may prevent a third one being inserted:
if(count(mysqli_fetch_array($result_check)) > 0) {
For some reason inputs in my login page don't seem to be getting processes correctly. Correct user inputs are getting returned as invalid (wrong password) having had a look through, I can't see anything particularly obvious. But I can only assume the username or password isn't getting passed for some reason. Would someone more experienced be able to take a look and suggest how I can put it right. Thanks guys. P.S My form is OK, so not included.
function logcon($user, $password )
{
$user = mysqli_real_escape_string($this->conn, $user);
$esc_password = mysqli_real_escape_string($this->conn,$password);
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
$result = mysqli_query($this->conn, $sql);
$row = mysqli_fetch_array($result);
return $row;
}
Login page.
if(isset($_POST['submit'])){
$user=$_POST['user'];
$password=$_POST['password'];
//To ensure that none of the fields are blank when submitting the form if
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = stripslashes($user);
$password = stripslashes($password);
$db1=new dbmember();
$db1->openDB();
$row=$db1->logcon($user, $password);
if($row[0]==1)
{
session_start();
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
$_SESSION['loggedin'] = "true";
header("location:index.php");
}
else
{
print ('<div id="error">Acess denied, wrong username or password?</div>');
}
}
else
{
print ('<div id="error">Enter something!</div>');
}
}
It appears you are using the wrong variable name in your query. I would also suggest you look into doing some sort of hashing and salting of your passwords instead of saving them as plain text.
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
should be
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$esc_password}'";
And your conditional check seems off, you are checking to see if the first field in the results is = 1 instead of seeing if there is a return.
if($row[0]==1)
Should probably be
if($row)
I wrote a login system using flex and php, but for some odd reason the php echos back both "true" and "false". Any ideas why this is happening?
<?php
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
//include("connect.php"); // used for your connection to the database.
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
// Temp username and password until hooked up to a database.
$strDetails[0] = "dennis";
$strDetails[1] = "test";
// DATABASE WORK HERE (grab the user)
/*<!--
$query = "SELECT username,password from users where username='$username' AND password='$password'";
while ($row = mysql_fetch_array($query)) { // have not tested yet.
if ($row['username'] == $username && $row['password'] == md5($password)) // If you don't want encryption take off md5
echo "<login>true</login>";
else
echo "<login>false</login>";
}-->
*/
// Temp until hooked up to a database.
if ($username == $strDetails[0] && $password == $strDetails[1])
echo "<login>true</login>";
else
echo "<login>false</login>";
?>
I had a similar problem several months ago. For some reason one of my loops wasn't parsing correctly.
Can you try changing the Temp login validation to:
// Temp until hooked up to a database.
if (($username == $strDetails[0]) && ($password == $strDetails[1])) {
echo "<login>true</login>";
} else {
echo "<login>false</login>";
}
Let me know how you get on, if that doesn't fix it I'll dig up the old troublesome script.