I want this code to check if $name and $password from form login is in database, if it true it shows echo "Hello ".$name; if not echo "You are not in database";, but the problem is it always shows the truth.
Thanks for your answer and sorry for my english)
include "db.php";
$db = db();
/*print_r($db);*/
$name = $_POST["name"];
$password = $_POST["password"];
$qur = "SELECT * FROM login WHERE name ='".$name."' AND password = '".$password."'";
$data_from_table = $db->query($qur);
if($data_from_table == true)
{
echo "Hello ".$name;
}
else
{
echo "You are not in database";
}
$data_from_table is not true but the result object from the query. But it will be false if the user is not in the db because there is no result.
change it to
if($data_from_table!==false) {
some well meant advice: never save passwords in real text in databases, i mean like ever. Here is some php function that will get you on track:
https://www.php.net/manual/de/function.password-hash.php
According to the documentation the PDO::Query function returns a PDOStatement object or false, if it didn't work well. Why did you was true. Documentation
Why do you check it with true, try checking it with false instead so if it is not false, you can catch your $name
The new version of mysql in PHP is no longer maintained,use PDO::Query function
Check the returned data of $data_from_table, is a data set
Related
for some reason my login script in php keeps returning invalid results, I'm using PHPMYADMIN to handle the database and mysqli to connect however whenever I submit the data though a HTML form the values always return false even if the correct username and password combo is working.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysql_connect("localhost","cnathanielwcol","","login");
if(! $con){die('Connection Failed'.mysql_error());}
$result = mysqli_query("SELECT * FROM login");
$row = mysql_fetch_array($result);
var_dump($row);
if ($row["username"]==$username) {
echo "Correct Username<br>";
} else {
echo "Wrong Username<br>";
}
if ($row["password"]==$password) {
echo "Correct Password<br>";
} else {
echo "Wrong Password<br>";
}
echo "<br><br>Username Submited Via HTML: <b>" . $username . "</b>";
echo "<br>Password Submited Via HTML: <b>" . $password . "</b>";
?>
MySQL is deprecated from new version of PHP use
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
Firstly, you need to select a single row, not all the rows in your table, you'd do that by specifying a WHERE clause, currently, you are trying to compare an array of values to a string which should be throwing an error if error reporting is enabled.
Secondly, you are mixing to different APIs, mysql_* is not mysqli_*.
Thirdly, it doesn't seems as though you are hashing your passwords, please, do so.
Fourthly, make use of prepared statements, it seems as though you are still learning so it would be best to start using them now.
Reading Material
OWASP's Password Storage Cheat Sheet
OWASP's PHP Security Cheat Sheet
Could you use mysqli_* please? You might be having a problem with your html form maybe
Change
$con = mysql_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
With
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
Your are trying to fetch the data with mysqli and your database connection is established by mysql
your full code:
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysqli_connect("localhost","cnathanielwcol","","login") or die('connection is not establised'.mysqli_error($con));
$result = mysqli_query($con,"SELECT * FROM login WHERE username='$username' AND password='$password'");
$rowCheck=mysqli_num_rows($result);
if ($rowCheck>0) {
// fetch all data
//start session
echo "you are logged in ";
}
else{
echo 'username or password did not match';
}
Use hash password.your code is not safe.
I am trying to set up a simple php login system with a mysql database and a simple php script. it seems to be working with one minor error; You can also login with the wrong credentials.
You can see it in action at rietool.roxtest.nl.
My code:
<?php
// get values passed from form in login.php file
$username = $_POST['username'];
$password = $_POST['password'];
// to prevent mysql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// connect to the server and select database
mysql_connect("my database info");
mysql_select_db("roxtest_nl_RIEtool");
// query the database for username
$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);
if ($row['username'] == $username && $row['password'] == $password) {
echo "login geslaagd, welkom";
} else {
echo "login mislukt, probeer opnieuw";
}
?>
If anyone could help me ou, that would be greatly appreciated!
FYI I followed this tutorial: https://www.youtube.com/watch?v=arqv2YVp_3E
First, as others already said, ur code is insecure !
Never use MYSQL_ even with _escape !
Learn how to use PDO which is more easy to use and can be more secure if u use it correctly !
In ur code, u already get :
where username = username and password = password in ur query
So it will return true or false, and u don't need to use if to compare username and password !
U just need the row count, if it's 1, the username and password is correct and if it's 0, they are incorrect !
It's not entirely clear what is happening here. But my guess is that:
$username = mysql_real_escape_string('foo');
Evaluates to false. Because it relies on a database connection that you haven't yet started. Same for the password.
Then later you get an empty result set:
$row = mysql_fetch_array($result);
$row is false. ("SELECT * FROM USERS WHERE username='' AND password=''";)
Then you have:
if ($row['username'] == $username && $row['password'] == $password) {
Which equates to:
if(null == false && null == false) {
Becomes:
if(true && true) {
So we have:
if(true) {
echo "login geslaagd, welkom";
}
So any credential will satisfy this!
Be very careful!
So to fix, make the connection before your calls to mysql_real_escape_string, or better, pass mysql_real_escape_string your database connection. You may want to check that the function doesn't return false either.
Then later make sure you have a row.
if(
$row = mysql_fetch_array($result)
&& $row['username'] == $username
&& $row['password'] == $password
) {
echo 'Success';
}
As mysql functions are deprecated you may wish to rewrite your example using a different database interface, and take on board some of the other feedback.
And look into error reporting and logging in Php. It would have helped you here.
Currently been at this for few hours now and desperately need a fresh set of eyes. When log in takes place a form is loaded to test encrypted password and username against the database, as it stands there are no errors showing up in the form when it is run but simply when it is run it denies the data from the user currently in the database being passed through.
I also recieve the final else statement giving me "Access Denied" any help would be hugely appreciated just need a fresh set of eyes, thanks alot. also to add all the $data instances are fields within the database
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$databaseName = "filestackusers";
$connect = new PDO("mysql:host=$serverName;dbname=$databaseName",$username, $password);
//encrypt pass and user for search
if(isset($_POST["username"]) && isset($_POST["password"]))
{
$FolderEncryption = md5($_POST['username']);
$passwordEncryption = md5($_POST['password']);
}
else
{
echo "information not passed";
}
try
{
//search if found load info
$checkSqlStmt = $connect->prepare("SELECT * FROM users WHERE user_folder =
:FolderEncryption AND password = :passwordEncryption");
//bind
$checkSqlStmt->bindParam(':FolderEncryption', $FolderEncryption, PDO::PARAM_STR);
$checkSqlStmt->bindParam(':passwordEncryption', $passwordEncryption, PDO::PARAM_STR);
//execute
$checkSqlStmt->execute();
$data = $checkSqlStmt -> fetchAll();
}
catch (Exception $ex)
{
die("An error has occured! " . $ex->getMessage());
}
if ($data)
{
if($_POST["username"] == $data[0]["username"]) //recheck email security
{
echo 'Access Granted';
$_SESSION['userID'] = $data[0]['user_id'];
$_SESSION['Username'] = $data[0]['username']; //set sessions
$_SESSION['Password'] = $data[0]['password'];
$_SESSION['Email'] = $data[0]['email'];
$_SESSION['UserFolder'] = $data[0]['user_folder'];
//load user info
loadFileInformation();
}
}
else
{
echo "Access Denied";
}
?>
You only echo access denied when $data evaluates to false. That can be the case when you don't assign it at all, which happens when you get an exception when executing the query. If there is no exception, fetchAll might still return false in case of an error.
But also, if the query executes correctly but returns no rows, fetchAll() returns an empty array, which also evaluates to false in PHP. (I don't make this stuff up!)
So whichever the case, it is due to the execution of the query.
Chances are that your $data variable is false so your code is echoing "Access Denied". You should set your condition to check that $data equals what you want it to and then proceed.
For Example:
if ($data == "Blah"){
if($_POST["username"] == $data[0]["username"]) //recheck email security
{
//Blah Blah
}
}else{echo "Access Denied";}
As opposed to:
if ($data)
{
if($_POST["username"] == $data[0]["username"]) //recheck email security
{
//Blah Blah
}
}else{echo "Access Denied";} // etc
The point is that your condition should be more precises. Whether using fetchAll or what ever.
I converted my login page to use PDO but now it's not working. I've run through all kinds of code examples and I can't figure out where I'm going wrong. This looks perfect to me. Also error reporting is fully enabled and yet I don't get any errors. I just get the browser error for the page being "incorrectly configured". FYI, this is a SQL db
//Code
<?php
require ("../Android/connect_db.php");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query_unpw = $db->prepare("
SELECT member_mast.company_name
FROM member_mast
WHERE username = ?
AND password = ?
");
//$username = $_POST['username'];
//$password = $_POST['password'];
$username = 'abc';
$password = 'abc';
$name = "name";
$query_unpw->bindValue(1, $username, PDO::PARAM_STR);
$query_unpw->bindValue(2, $password, PDO::PARAM_STR);
$query_unpw->execute();
$count = $query_unpw->rowCount();
if ($count > 0) {
while ($row = $query_unpw->$fetch(PDO::FETCH_ASSOC)) {
$name = $row['company_name'];
}
echo $name;
} else {
echo "Username/Password is invalid";
}
} catch(PDOException $e) {
die($e->getMessage());
}
?>
Now the only thing I've been able to figure out after commenting out different pieces of code is that if I comment out the username and password, like this
//$username = 'abc';
//$password = 'abc';
Then the page loads and just gives me my else echo of "Username/Password is invalid". However I don't think I'm using them wrong and I know they are correct. So the obvious question is am I blind, what's wrong here? The bonus question is, since I will be using _POST for these variables when this works, am I properly sanitizing the user inputs? Still really new to PDO and I want to make sure I'm doing this right. Thanks for the help!
Problem is here:
$query_unpw->$fetch
It must be:
$query_unpw->fetch()
It's a method, so skip that $ sign.
I suggest you to use ini_set('display_errors', "On") while developing.
Okay.. I am completely new to this PDO stuff.. I have tried to recreate my mysql script (working) to a PDO script (not working).. I have tested that my DB login informations is correctly programmed for PDO..
This is my PDO script...
<?
session_start();
//connect to DB
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the email and password
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
$sql -> execute();
$count = $sql->rowCount();
$result = $sql -> fetch();
// Now use $result['rowname'];
$stmt = $conn_business->prepare("SELECT * FROM members WHERE email='".$email."'");
$stmt ->execute();
$act = $stmt -> fetch();
//if email exists
if($count > 0)
{
//compare the password
if(strcmp($result["password"],$pass)==0)
{
// check if activated
if($act["activated"] == "0")
{
echo "act"; //account is not activated yet
}
else
{
echo "yes"; //Logging in
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no"; //Passwords don't match
}
else
echo "no"; //Invalid Login
?>
And this is my old mysql script...
session_start();
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the username and password
$sql="SELECT email, password members WHERE email='".$email."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$sql2="SELECT * FROM members WHERE email='".$email."'";
$result2=mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$act = $row2['activated'];
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
// check if activated
if($act == "0")
{
echo "act";
}
else
{
echo "yes";
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no";
}
else
echo "no"; //Invalid Login
Does anybody know, what I have done wrong? It is an automatically script.. It is called through AJAX and return data based on 'no', 'yes' and 'act' that tells the AJAX/jQuery script what to do.. As I said - the mysql script is working, so please if anyone could tell me what I have done wrong with the PDO script..
EDIT:
when it returns the data to the jQuery script, this should happen:
if yes: start session, redirect to page2.php with session started.
else if act: write in a field that the account is not activated.
else: write that email and password didn't match.
The thing is, that when I try to write the correct e-mail and password - it continues to write : "email and password didn't match" instead of redirecting.. When I say that it is not working it is because the mysql script does as described but the PDO script doesn't..
And I have tried to change the 'echo "no";' to 'echo "yes";' to see if the login would start anyway, but somehow it continues to write that the email and password didn't match..
SOLUTION:
I ahven't told this because I thought it was unnecessary, but the reason for it not to work was because of that i have had my old mysql code in comment marks on top of the page, so that the session_start command didn't work.. After deleting the old code it worked, but then I found something else to change, and that is in the PDO script when it is validating it says:
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
and then I just changed the '-' after $sql to '=' and now, everything works perfectly... Anyhow thank you everybody.. hope this code can help others..
Did you even read the manual before you "started using" PDO?
That is not how prepared statements are supposed to be used! Your code is filled with SQL injections.
Why are you selecting same row twice ?
The strcmp() is not for checing if one string is identical to another.
And hashing passwords as simple MD5 is just a sick joke.
session_start();
//very stupid way to acquire connection
require_once("connect.php");
//get the posted values
$email = htmlspecialchars($_POST['email'],ENT_QUOTES);
if (filter_var( $email, FILTER_VALIDATE_EMAIL))
{
// posted value is not an email
}
// MD5 is not even remotely secure
$pass = md5($_POST['psw']);
$sql = 'SELECT email, password, activated FROM members WHERE email = :email';
$statement = $conn_business->prepare($sql);
$statement->bindParam(':email', $email, PDO::PARAM_STR);
$output = 'login error';
if ($statement->execute() && $row = $statement->fetch())
{
if ( $row['password'] === $pass )
{
// use account confirmed
if ( $row['activated'] !== 0 ) {
$output = 'not activated';
$_SESSION['email'] = $email;
}
$output = 'logged in';
}
}
echo $output;
i believe the second query in your scripts is not necessary you could simple do
SELECT * FROM members WHERE email=:EMAIL AND password=:PWS;
use bindParam method
$qCredentials->bindParam(":EMAIL",$EMAIL);
$qCredentials->bindParam(":PWS",$PWS);
then do more understable outputs rather than yes or no..
try "Unable to login: Invalid credentials supplied" for invalid types of values or "Unable to login: Invalid credentials, couldn't find user" for invalid user credentials.
You could try to start the session after the user has been successfully logged in your IF condition returning yes, and the methods
$PDOstatement->debugDumpParams()
$PDOstatement->errorInfo()
$PDOstatement->errorCode()
will help you understand what went wrong with a query!