Password Reset with Personal Verification [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
I am new to php trying to learn something.I'm trying to write a script which allow users to reset password after they verify their personal info. Everything is working good except this php script. This script receives data from form input fields. The program was supposed to output:
echo $e.'&u='. $us .'&er='.$err.'&o='. $bulls3 .'&r='.$bulls4;
exit();
which can be sent to ajax as respondText.
The problem is this php script is not working as expected and giving me following error msg. Is there anyone who can help me out. Any help will be very much appreciated. Thank you in advance for help..
Error Output Message:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\myGenius\identityverify.php on line 119
contact
<?php
// AJAX CALLS THIS CODE TO EXECUTE
if(isset($_POST["bd"])){
$bad= preg_replace('#[^0-9-]#i', '', $_POST['bd']);
//Connect to database
include_once("php_includes/connect_to_mysqli.php");
$e = mysqli_real_escape_string($db_conx,$_POST['e']);
$c= preg_replace('#[^a-z ]#i', '', $_POST['c']);
$post= preg_replace('#[^a-z0-9]#i', '', $_POST['pst']);
$user= preg_replace('#[^a-z0-9]#i', '', $_POST['us']);
$odd= preg_replace('#[^a-z0-9]#i', '', $_POST['od']);
if($e =="" || $bad =="" || $c=="" ||$post==""){
echo "empty";
exit();
}else if($user=="" || $odd==""){
echo "no_exist";
exit();
}else{
$sql = "SELECT id, username FROM user WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$u = $row["username"];
//Encrypted values to check with user input passed from hidden fields
//Check codes
$bull= value1;
$bull2= value2;
$bull3= value3;
$bull3=value4;
$us= value5;
$err= value6;
}
if($user==$us && $odd==$err){
$sql = "SELECT country, birthday, postal FROM useroptions WHERE email='$e' AND username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$con = $row["country"];
$bday = $row["birthday"];
$poost = $row["postal"];
}
if($c == $con && $bad == $bday && $post==$poost){
// encoded value using some type of encryption for passing data to another web page based on user information data
$bulls= value1;
$bulls2= value2;
$bulls1=value3;
$bulls3= value4;
$bulls4= value5;
$bulls3=value6;
$bulls4=value7;
echo $e.'&u='. $us .'&er='.$err.'&o='. $bulls3 .'&r='.$bulls4;
exit();
}else{
echo "wrong";
exit();
}
}else {
echo "contact";
exit();
}//user option not set
}else{
echo "no_exist";
exit();
}//end code comparison and send to error page
}else{
echo "no_exist";
exit();
}
exit();
}}
?>

I always use two queries rather than making a server return everything that matches
select count(*) from database where condition='expected';
Perform a second query based on an if() clause validating the initial result.
This affords a precaution against injection since my main query hasn't been executed.
Try replacing
if(isset($_POST["bd"])){
With
if(!empty($_POST["bd"])){

Related

Php & MYSQL Login Script - Trying to get property of non-object *** on line 11

I´m trying to create a simple login script for my Website (with PHP & Mysql). Created the original script with plain php & mysql commands and everything worked just fine. Now i wanted to exchange the old mysql commands with mysqli commands. Somehow i´m now getting the error "Trying to get property of non-object *** on line 11" when I test my script. Could somebody explain exactly to me what causes that problemn and how to solve it (because I dont really understand the error here)?
Login Script:
<?php
session_start();
?>
<?php
include_once "db_connect.php";
$username = $_POST["username"];
$password = md5($_POST["password"]);
$abfrage = "SELECT username, password FROM login WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysqli_query($verbindung,$abfrage);
$row = mysqli_fetch_assoc($ergebnis);
if ($row->password === $password) { <--- Line 11
$_SESSION["username"] = $username;
if ($username != "admin") {
echo "Login erfolgreich. <br> Geschützter Bereich";
}
else {
echo "Login erfolgreich. <br> Geschützter Bereich";
}
}
else {
echo "Benutzername und/oder Passwort sind falsch.";
}
?>
$row is an associative array, because you have used $row = mysqli_fetch_assoc($ergebnis); but you are treating $row as an object i.e.
$row->password
So try:
if ($row['password'] === $password)
<?php
session_start();
include_once "db_connect.php";
// either use require_once + bail-out code in db_connect.php
// or check the connection resource/object here.
if ( !$verbindung || $verbindung->connect_errno ) {
die('sorry, db error. try again later');
}
$password = md5($_POST["password"]); // md5, unsalted ...not secure anymore. see http://docs.php.net/password_hash
// see http://php.net/security.database.sql-injection
$abfrage = sprintf( // password is a reserved word in mysql -> backticks around the field id
"SELECT `username`, `password` FROM login WHERE username LIKE '%s' LIMIT 1",
mysqli_real_escape_string($verbindung, $_POST["username"])
);
$ergebnis = mysqli_query($verbindung,$abfrage);
// mysqli_query may fail at any time -> error handling required
if ( !$ergebnis ) {
echo 'db query failed'; // $verbindung->error should contain more information
}
else if ( !($row = mysqli_fetch_assoc($ergebnis)) ) {
echo 'no result'; // you probably shouldn't make a distinction between "no such record" and "wrong password" - just for illustration
}
else if ($row['password'] === $password) { // fetch_assoc returns an array, not an object
$_SESSION["username"] = $username;
}
use that like this
$row = mysqli_fetch_assoc($ergebnis);
if ($row['password'] === $password) {
Try with $row["password"]==$password
If it still shows the same thing, then var_dump $row and see if it returns a result.

Why can't I echo out a variable from an array?

I'm sorry if this has been asked, but I have no idea what to search for to find an answer.
I'm just starting to learn PHP and am doing a simple tutorial where I'm "logging into" a data base (just checking to see if the email and password match what is stored no actual session is being created).
I have this code:
<?php
include("connectToDb.php");
$loginEmail = $_POST['loginEmail'];
$loginPassword = $_POST['loginPassword'];
$query = mysqli_query($dbc, "SELECT * FROM users WHERE email='$loginEmail'");
$numrows = mysqli_num_rows($query);
if($numrows != 0)
{
while($row = mysqli_fetch_array($query))
{
$dbemail = $row['email'];
$dbpassword = $row['password'];
$dbfirstname = $row['firstName'];
}
if($loginEmail == $dbemail)
{
if ($loginPassword == $dbpassword)
{
echo "Hi ".$row['firstName'].", you are now logged in.";
}
else
{
echo "login failed.";
}
}
}
mysqli_close($dbc);
?>
But the $row['firstName'] in the echo statement prints as a blank string: "Hi , you are now logged in.". If I use the exact same code but repalce $row['firstName'] with $dbfirstname in the echo statement, I get a properly formatted message "Hi Jason, you are now logged in.".
Those two variables are supposed to be the same... why does one work while the other does not?
Check the control flow:
You have the while loop while($row = mysqli_fetch_array($query)) - so you assign a new value to $row and test it. If it evaluates to false (i.e. no more rows), you break the loop.
This implies, that after the loop $row no longer has valid content. Your stored values (e.g. $dbfirstname) are from the previous iteration of the loop and thus contain valid data.

How to debug PHP database code?

I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";

PHP and Oracle Session Login

Here it's I have a problem with my PHP Code + Oracle Login form.
In this PHP file, I make login function. But I have an error like this :
Warning: oci_num_rows() expects parameter 1 to be resource, string given in C:\xampp\htdocs\developers\it\session.php on line 12
Wrong
-
<?php
session_start();
include ("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$do = $_GET['do'];
if($do=="login")
{
$cek = "SELECT PASSWORD, USER_LEVEL FROM T_USERS WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = oci_parse($conn, $cek);
oci_execute($result);
if(oci_num_rows($cek)==1)
{
$c = oci_fetch_array($result);
$_SESSION['username'] = $c['username']; ociresult($c,"USERNAME");
$_SESSION['USER_LEVEL'] = $c['USER_LEVEL']; ociresult($c,"USER_LEVEL");
if($c['USER_LEVEL']=="ADMINISTRATOR")
{
header("location:supervisor.php");
}
else if($c['user_level']=="User")
{
header("location:user.php");
}
else if($c['user_level']=="Root")
{
header("location:administrator.php");
}
else if($c['user_level']=="Manager")
{
header("location:manager.php");
}
else if($c['user_level']=="Admin")
{
header("location:admin.php");
}
else if($c['user_level']=="Director")
{
header("location:director.php");
}
}
else
{
echo "Wrong";
}
}
?>
I have tried to search in google, but still don't find anything.
Someone knows, what's the problem ?
Thanks for advance.
According to your script instead of
if(oci_num_rows($cek)==1)
you should call
if(oci_num_rows($result)==1)
You probably want to use $result and not $cek when you're asking for the number of rows returned from oci_num_rows(). However, you really want to avoid using $username and $password directly in the string like that. It'll make you wide open for SQL injection attacks, so look into using oci_parse together with oci_bind_by_name.
After that you should also always call exit() after the sequence of redirects, as the script will continue running if you don't (and that might be a security issue other places).
I also got the same case, so I tricked it with a script like this, but I don't know whether there was an impact or not. because the session and validation went smoothly.
$username =$_POST['username'];
$password = $_POST['password'];
$conn = oci_connect('xxx', 'xxx', 'localhost/MYDB');
$pass_encription = md5($password);
$query = "SELECT * from *table_name* WHERE *field1*='".$username."' and *field2*='".$password."'";
$result = oci_parse($conn, $query);
oci_execute($result);
$exe = oci_fetch($result);
if ($exe > 0)
{
oci_close($conn);
oci_execute($result);
$row =oci_fetch_array($result);
$sid = $row['field_1_parameter'];
$snama = $row['field_2_parameter'];
$sjab = $row['field_3_parameter'];
$session = array (
'field_1_array' =>$sid,
'field_2_array' =>$snama,
'field_3_array' =>$sjab
);
if($sjab == 'Administrator')
{
$this->session->set_userdata($session);
redirect('redirecting_page');
}
`

This if statement isn't working - what am I doing wrong?

I'm trying to retrieve the access level (admin/member/guest) for the currently logged in user and depending on this, show them specific content on my page. I'm trying to test this with echos right now but still cannot get anything to print out. Could anyone give any advice?
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' ";
$result = mysql_query($q, $con);
if($result == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($result == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($result == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result is a mysql resource. you need
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if($access == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($access == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($access == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result as returned by mysql_query is not a string that you can compare against; it is a resource. You need to fetch the row from $result:
$row = mysql_fetch_assoc($result)
$access = $row['access'];
if($access == 'guest') {
...
}
...
A few other issues:
You have a possible SQL-injection issue in your query. You should never directly insert the values of variables into your SQL queries without properly escaping them first. You might want to use mysql_real_escape_string.
The mysql is being deprecated. You should try to use mysqli (MySQL Improved) or PDO (PHP Data Objects).
I see two issues:
1. You need to use session_start(); at the beginning. otherwise your if statement will not be executed.
2. mysql_query($q, $con) does not return a string. it returns a record set. You need to use mysql_fetch_assoc($result); which return associative array.And from the array you retrieve your desired value by:
$assoc_arr = mysql_fetch_assoc($result);
$access = $assoc_arr['access'];
now you can compare $access.

Categories