Why is my $opword not equal to $query - php

Hello i want to change my password which is coming from my database, the very first thing i want to verify the users old password, but my $query is not equal to $opword, what might be the reason ?
I am trying to get the result from past 8 hours but I dont know where I went wrong please do help me thanks in advance.
<?php
session_start();
require_once('../includes/config.php');
if(isset($_POST['submit'])) {
require_once('../includes/config.php');
$opword = $_POST['opword'];
$npword = $_POST['npword'];
$cpword = $_POST['cpword'];
$string = "SELECT password FROM admin WHERE username = '$_SESSION[uname]'";
$query = mysqli_query($dbc,$string);
if($opword == $query) {
echo "yup";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
require_once('includes/menu.php');
?>
<form action="changepassword.php" method="post">
<p><label>Old Password:</label><input type="password" name="opword"></p>
<p><label>New Password:</label><input type="password" name="npword"></p>
<p><label>Confirm Changed Password:</label><input type="password" name="cpword"></p>
<input type="submit" value="Change Password" name="submit">
</form>
</body>
</html>

Because you are try to compare password with result object. You need to fetch password field form your data result
if($opword == $query->password) {// fatch password form result data
Note:- Don't store plain password into database
Read http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/faq.passwords.php

Don't forget to use prepared statements and hash your passwords before store them in database (password_hash).
$session_username = $_SESSION['uname'];
//Take only one username
if ($stmt = $dbc->prepare("SELECT password FROM admin WHERE username = ? LIMIT 1")) {
$stmt->bind_param("s", $session_username);
$stmt->execute();
$stmt->store_result();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row['password'] == $opword) {
echo 'yup';
}
}

After the following statement:
$query = mysqli_query($dbc,$string);
Use this before comparing compare:
$row = mysqli_fetch_array($query);
if($opword == $row[0]) {
echo "yup";
}

By using xdebug or var_dump(), you would find that $query is a PDOStatement, and object which will never equal a word.
You need a function get the data. Here is the documentation for mysqli queries.

Basically
$query = mysqli_query($dbc,$string);
mysqli_query returns a resource not value. So you have to fetch values from it
mysqli_fetch_assoc or mysqli_fetch_array
any of above function can be used. Both function returns array. Then you can use array value to match with other value. Hope it will help you.

Related

Log in cant find error

Hi i am trying to create a very simple log in function using PHP however, after going through the codes, my form seem to be able to perform the function right only when i enter the right user name and password however, if i dont, it doesnt perform its duties here are my codes that i have simplified :
login.php
<form name="userlogin" action="phpprocess/loginprocess.php" method="POST">
<p>Username : <input type="text" id="username" name="username"></p>
<p>Password : <input type="password" id="password" name="password"></p>
<p><input type="submit" id="loginbtn" value="login" ></p>
</form>
loginproccess.php
include "mysqli.connect.php";
$username = $mysqli->real_escape_string($_REQUEST["username"]);
$password = $mysqli->real_escape_string($_REQUEST["password"]);
echo "$username";
echo "$password";
$sql = "select * from users.userlogin where username ='".$username."' and
password = '".$password."'";
$result = $mysqli->query($sql);
if($result == null){
echo"null";
}
if($mysqli -> errno){
error_log($mysqli -> error);
echo $mysqli -> error;
echo " hello";
exit();
}else{
while( list($index, $user1, $pass1) = $result -> fetch_array()){
if($user1 != null && $pass1 != null){
echo "$index $user1, $pass1";
}
}
}
$mysqli->close();
mysqli.connect.php
$host="localhost";
$user="root";
$password="";
$database="users";
$mysqli = new mysqli($host, $user, $password, $database);
if ($mysqli->errno) {
echo "Unable to connect to the database: <br />".$mysqli->error;
exit();
}
what happens is if i enter the wrong user name and password i need the webpage to echo hello , if i enter it right i need it to echo the right user and pass but when enter wrongly, $result does not seem to be null as null and hello is not being printed out. My error log does not display anything. Hope to hear your advice! Thank you in advance !
You print hello when the query gets an error, but it's not an error if the WHERE conditions don't match any rows. It just returns an empty result set. You should use:
if ($result->num_rows == 0) {
echo "hello";
exit();
}
Also, $result->fetch_array() returns an array with both numbered and named indexes. If your table has 3 columns, this will return an array with 6 elements, but you're only assigning to 3 variables.
Use $result->fetch_row() to get an array with just the numbered elements. Also, you shouldn't use SELECT * if you're relying on the order of elements like this, since that depends on the order that the columns were assigned in the CREATE TABLE statement, and this might change if you update your schema. You should list the specific columns you need in the SELECT list.

PHP Login system doesnt display anything after i hit login

The PHP code is as follows:
<html>
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost", "root", "");
mysql_select_db("login");
$result = mysql_query("select * from users where username = '$username' and password = '$password'")
or die ("Failed to query database ".mysql_error());
$row = mysql_fetch_array($result);
$dbusername = $row['username'];
$dbpassword = $row['password'];
if ($username == $dbusername); {
echo "login succesfull";
}
else
{
echo "failed to login";
}
?>
</html>
and the login page code is:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<img src="WCCS Logo.png" id="schoollogo">
<div id="frm">
<form action="process.php" method="POST">
<p>
<label>Username: </label>
<input type="text" id="user" name="user"/>
</p>
<p>
<label>Password: </label>
<input type="password" id="pass" name="pass" />
</p>
<p>
<input type="submit" id="btn" value="login" />
</p>
</form>
</div>
</body>
The database is named login and the table is called users
it has id, username, password, first name and last name columns with entered information.
For some unknown reason when I click the submit button it brings up a blank page, although the url changes to the page and when I add some type of text like a html paragraph it displays it.
So it goes to the page, also there is a css file if needed, it was working a couple days ago and now it is not. I dont understand what is wrong with it.
It is like the PHP doesnt even get run, its just ignored
I want to clear few points:
Mysql is deprecated so use of mysqli and PDO is good practice now onward.
As per your code it seems that you haven't stored encrypted password in DB. You must have to encrypt password for security purpose.
You are comparing your username and password in your query itself then why are you comparing it again in PHP code.
Please try below code instead:
<?php
$con=mysqli_connect("localhost","root","","login");
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$result = mysqli_query($con, "select * from users where username = '".$username."' and password = '".$password."'") or die ("Failed to query database ".mysqli_error());
$row = mysqli_fetch_array($result);
if (!empty($row)) {
echo "login succesfull";
}
else{ echo "failed to login"; }
?>
Several problems/bad practice...
1: Don't save passwords in plaintext in your database. Use some encryption like hash+md5.
2: Don't use mysql. Use mysqli or PDO instead.
-> http://php.net/manual/de/book.mysqli.php
-> http://php.net/manual/de/book.pdo.php
3: Some logic: Take a look at your SQL query. You're selecting from users where Username & password correspond to the values entered by the user. So, what this means? If the query will find an entry, the data will be automatically correct, cause if you put in a wrong password the statement won't return any data, so your if statement is unnecessary.
By doing this:
$dbusername = $row['username']
$dbpassword = $row['password']
(btw, ; is missing here at the end of the two lines) your just assigning the returned data from the database to the variables. But its just logic that $dbusername will always correspont to $username, because as i said, you just handled the SQL statement this way.
I think you're quite new to programming, or at least new to PHP. I really recommend you to take a look at mysqli and google for some login systems, take a look at those examples and rewrite your code.
Btw, i don't know what you're knowing about sessions, but i'm quite sure you'll start a session when you log in, so may thats another keyword too you can google.
$dbusername = $row['username']
$dbpassword = $row['password']
These should be changed too
$dbusername = $row['username'];
$dbpassword = $row['password'];
A white page (with errors turned on) is a good indication that you've missed one of these: ()[]{};.
This line has an extra ';'. So change this:
$result = mysql_query("select * from users where username = '$username' and password = '$password'");
or die ("Failed to query database ".mysql_error());
to this:
$result = mysql_query("select * from users where username = '$username' and password = '$password'")
or die ("Failed to query database ".mysql_error());
The culrpit was password = '$password'"); or die

sql query fails every time

<html>
<head>
</head>
<body>
<form action="login_process.php" method="post">
SID: <input type="text" name="sid">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
login_process.php FILE
<html>
<head>
</head>
<body>
<?php
include ("connection.php");
$sid = $_POST['sid'];
$pw = $_POST['pw'];
setcookie("username", "$sid". time()+86400);
$result = mysqli_query($con, "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'") or die('Query failed');
if(!$result){
echo "Failed";
} else {
echo "success". $_COOKIE['username'];
$_SESSION['username'] = $sid;
}
?>
</body>
</html>
I have data in my student_table. But no matter what input i give it says success. even if i click login button without any input it still says success. please help.
You should use quotes when you assign values in sql queries .
SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'
Also look forward Prepared Statements to protect yourself from sql injections.You should also add the code below to fetch selected row :
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['SID'];
}
Start learning basic debugging:
When a query fails bad, just do this:
Instead of running it (mysql_query, or mysqli_query or whatever you have), ECHO it:
echo "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'";
After you submit the form, you will be shown the query that runs, go to phpmyadmin or whatever you use and run the query manually. See if there are errors and also see easier what's going on. Advisable when you do work like this, FIRST try the queries in phpmyadmin then apply them in the code, after you are confident they are ok.
This is not really an answer but more about how to find out what is going wrong when you code does not work as you expect.
First, always put you SQL into a variable by itself. Why, so you can 'var_dump' it and see what is happening. So, try this:
$sql = "SELECT SID FROM student_table WHERE SID=$sid and password=$pw";
var_dump($sql, 'my_query'); // you will see what PHP created.
then try the answer provided:
$sql = "SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'";
At least you will see what is likely to be incorrect.
var_dump($sql, 'the answer_query'); // you will see what PHP created.
$result = mysqli_query($con, $sql) or die('Query failed');
The outer quote marks must be " (double quote) not " ' " (single quote) both of which are perfectly valid PHP. the former allows variables to be replaced in strings.
The latter will treat eveything as a literal string.

Error in if statement for user login page PHP

I am creating this page for as a login system, the database connects fine, I don't see any errors or get any errors, the problem is when I enter right username and password i get this:
"SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."
and when I enter an incorrect username and password I get a blank page.
<?php
include_once("db_connection.php");
$userName = $_POST['user'];
$password = $_POST['password'];
if($userName == "" || $password == ""){
echo "Fill in both field";
exit;
}
function SignIn(){
session_start(); //starting the session for user profile page
if(!empty($_POST['user'])) //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM Customer WHERE userName = '$_POST[user]' AND password = '$_POST[password]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['password']))
{
$_SESSION['userName'] = $row['password'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
here is the HTML so everyone can see what I am trying to do:
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="style-sign.css">
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%"><legend>LOG-IN HERE</legend>
<form method="POST" action="connectivity.php">
User <br><input type="text" name="user" size="40"><br>
Password <br><input type="password" name="password" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
</fieldset>
</div>
</body>
</html>
Try:
$query = mysql_query("SELECT * FROM Customer WHERE userName = '{$_POST['user']}' AND password = '{$_POST['password']}'") or die(mysql_error());
Or to be safe:
$query = mysql_query("SELECT * FROM Customer WHERE userName = '" . mysql_real_escape_string($_POST['user']) . "' AND password = '" . mysql_real_escape_string($_POST['password'] . "'") or die(mysql_error());
Also i think you might want to use:
$row = mysql_fetch_assoc($query);
Rather than:
$row = mysql_fetch_array($query);
too many issues in your code,
1: you're wide open for sql injection because you're not sanitizing your variables.
2: you shouldn't still be using mysql_* as they are deprecated.
3: try your query like this:
mysql_query("SELECT * FROM Customer
WHERE userName = '".mysql_real_escape_string($_POST['user'])."'
AND password = '".mysql_real_escape_string($_POST['password'])."'");
4: Check your spelling, I spotted ENTERD which should be ENTERED
WARNING! WARNING!
Your code is vulnerable to injection. All I have to do is enter the username of my choice, and the password ' or '1 and it will let me in to anyone's account!
Use mysql_real_escape_string to escape the values and make them safe.
ALSO: You appear to be saving passwords as PLAINTEXT strings. This is bad. I mean really, really, really, REALLY bad. I cannot emphasize how monumentally bad this is. See the Hitchhiker's Guide on the size of the universe for an idea.
... Unless you're saving them in an encrypted format, and trying to access them as plaintext. That'll never work, you need to encrypt whatever the user inputs and see if it encrypts to the same thing.
Your SQL query string is using the literal value of $_POST[user], you should be concatenating the actual value of that into your String. And actually you should be escaping it to prevent SQL injection since this is posted from a client.
This thread explains injection: How can I prevent SQL injection in PHP?
Replace your SQL Statement with this:
SELECT * FROM Customer WHERE userName = '$userName' AND password = '$password'
That's assuming you don't want to do any sort of sanitizing. If you do, change your first lines to:
$userName = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['password']);

How to get the values in a database table to an array using php code?

I'm a beginner in the programming field..
My concept is just to move,to the home page from the login page after doing the checking of user id and password. i have a database table with fields 'user_id' & 'password'. so i want to get the datas from the table to array and then want to compare it with the values entered by the user...How is it possible in the most easiest way?
I always use
$query = "...";
$sql = mysql_query($query);
while($row = mysql_fetch_assoc($sql)) {
$user_id = $row['user_id'];
// ...
}
I think that should work better as you get an associative array, so you can work with the field names.
Note that if you're selecting SUM(*), you have to put $row['SUM(*)'] or give it a name via SQL.
Although you've shown little research and your question is quite broad, I'll show you an example that might give you some clues.
$username = mysql_real_escape_string($_POST['username']); //escaping the string, will use it in a query
$password = $_POST['password'];
$result = mysql_query("SELECT password FROM users WHERE username = '$username'");
if (mysql_num_rows($result) == 1) { // Expecting one result
$userdata = mysql_fetch_array($result);
if ($password == $userdata['password']) {
// USER IS AUTHORISED
} else {
// USER IS NOT AUTHORISED
}
}
This is a simple example.
Things to consider:
Although I did that in the example above to simplify things, do not store password as plaintext in the database - store a MD5 hash instead. You can generate a hash by using md5("string to hash"). If you need help with that start another question.
After you have authorised the user you can "remember" that by using PHP sessions. Again, if you need help with that ask another question.
$username="username";
$password="password";
//Specify MySQL database to connect to
$database="database";
//Create connection and select the appropriate database
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
//Get the username and password from posted form
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//Build the query to look for users that exist with that username/password combination
//Here I'm using the users table within my database
$query = "SELECT * FROM users where username=\"$username\" and password = \"$password\" ";
//Retrieve the results of the query, and also aquire the number of records returned
$result = mysql_query($query);
$num = mysql_numrows($result);
//Check to see how many records are returned
if ($num>0)
{
//User login was successful
echo 'success login';
} else {
//Login was unsuccessful
echo 'user name not found';
}
Try this
//HTML
<form method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="login" value="login"/>
</form>
//PHP
if(isset($_POST['login']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$query = "select username,password from tableName
where username='$username' and password='$password'";
$sql = mysql_query($query);
if(mysql_num_rows($sql) == 1)
{
// Login success save username in session redirect to homepage
header("location:homepage.php");
exit();
}
else
{
// Display error message
}
}

Categories