cant login after successfully register to database - php

This is my login code, cant figure out whats wrong ( the last if, always goes to the last else ). i tried everything but still no luck.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if($_POST['submit']){
include_once("connection.php");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$sql = "SELECT id, username, password FROM user WHERE username = '$username' AND password = '$password'";
$query = mysqli_query($connection, $sql);
if($query){
$row = mysqli_fetch_row($query);
$userId = $row[0];
$dbUsername = $row[1];
$dbPassword = $row[3];
}
if ($username = $dbUsername && $password == $dbPassword) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('Location: users.php');
}else {
header('Location: error.php');
}
}
?>
and thas my connection code
<?php
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('login');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>

You are going to kick yourself... you have only a single = in your if.
if ($username = $dbUsername && $password == $dbPassword) {
Should be
if ($username == $dbUsername && $password == $dbPassword) {
The single = turns it into an assignment instead of a comparison.
Beyond that you are actually doing the comparison twice; once in SQL to get back the username and password, the second time in PHP. If your query returns the user id, you already know that the username/password did the trick.
You are also mixing mysql_connect and mysqli_query (and mysql_fetch_row). As the others have suggested, you need to move to the mysqli class or to PDO. But to get you going, you need to at very least change mysqli_query to mysql_query and mysqli_fetch_row to mysql_fetch_row.

Use mysql_query($connection, $sql) instead of mysqli_query($connection, $sql);
as you are using mysql_connect

Related

password_verify returns false. cant find error [duplicate]

This question already has answers here:
Using PHP 5.5's password_hash and password_verify function
(4 answers)
Closed 3 years ago.
I have been trying to figure out this problem for about 2 months and can't seem to figure it out. I have a database that returns the hashed password. I can confirm this works due to printing out all the information. It can return the non-hashed and hashed password perfectly fine but when it checks the password it will always return false.
I am not sure what to do. It could be something really easy but I seem to not be able to find it.
<?php
session_start();
$dbip = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "projectNitro";
$conn = new mysqli($dbip, $dbuser, $dbpass, $dbname);
if($conn->connect_error) {
echo("Connection failed: " . $conn->connect_error);
}
$password = mysqli_real_escape_string($conn, $_GET["pass"]);
$email = mysqli_real_escape_string($conn, $_GET["email"]);
$sql = "SELECT * FROM users WHERE email='{$email}' LIMIT 1";
$query = mysqli_query($conn, $sql);
$pass = $_GET["pass"];
if($query == TRUE) {
$row = mysqli_fetch_array($query);
$db_password = $row['password'];
$db_usertype = $row['accountType'];
$username = $row['username'];
echo $password;
echo "<br>";
echo $db_password;
echo "<br>";
$verify = password_verify($pass, $db_password);
if($verify) {
$_SESSION['username'] = $username;
$_SESSION['at'] = $db_usertype;
header("Location: http://website.com");
} else {
echo("DB Email: "
.$row["email"]
."<br>Username: "
.$row["username"]
."<br>DB Password: "
.$row["password"]
."<br>AccountType: "
.$row["accountType"]
."<br>Inserted Email: "
.$_GET["email"]
."<br>Inserted Password: "
.$_GET["pass"]."<br>");
if(password_verify($_GET["pass"], $row["password"])) {
echo("epic<br>");
} else {
echo("not epic<br>");
}
}
} else {
header("Location: http://website.com");
}
$conn->close();
?>
You need to do baby steps. keep stepping up as long as it works.
Here is a simpler version of your code that should work with the password sample from the official doc: http://php.net/manual/en/function.password-verify.php
Also use die(); to debug your code in every {} block.
In your current code you redirect to a website in both cases it's really hard to track what is wrong if you are redirected!
You have useless and unclear variables, for instance $dbpass, $db_password is very ambiguous, even if you and I understand it makes it not maintainable. As well as your coding style, you need to indent!
The next step you need to check if this code works, is replace the hard coded password with a hard coded password you have with hard coded hash as well.
<?php
session_start();
$dbip = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "projectNitro";
$conn = new mysqli($dbip, $dbuser, $dbpass, $dbname);
if ($conn->connect_error){
echo("Connection failed: " . $conn->connect_error) . '<br><br>';
}
$password = 'rasmuslerdorf';//mysqli_real_escape_string($conn, $_GET["pass"]);
// $email = mysqli_real_escape_string($conn, $_GET["email"]);
// $sql = "SELECT * FROM users WHERE email='{$email}' LIMIT 1";
// $query = mysqli_query($conn, $sql);
// $pass = $_GET["pass"];
// if ($query == TRUE) {
// $row = mysqli_fetch_array($query);
$db_password = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
// $username = $row['username'];
echo $password;
echo "<br>";
echo $db_password;
echo "<br>";
if (password_verify($password, $db_password)) {
die('ok');
} else {
die('not ok');
}
// } else {
// header("Location: http://website.com");
// }
$conn->close();
?>
Here I modified slightly and added a few comments along the code to help you understand the approach.
<?php
session_start();
// This array is used only like a simple namespace.
$dbCredentials = [
'host' => "localhost",
'user' => "root",
'password' => "",
'dbname' => "projectNitro"
];
$dbConn = new mysqli($dbCredentials['host'], $dbCredentials['user'], $dbCredentials['password'], $dbCredentials['dbname']);
if ($dbConn->connect_error) {
// Should not continue script if can't connect to DB.
die("Connection failed: " . $dbConn->dbConnect_error);
}
// You should check the existence of $_GET["pass"] before using it, with empty() or isset().
$passwordToCheck = mysqli_real_escape_string($dbConn, $_GET["pass"]);// Renamed var more meaningful.
$userEmail = mysqli_real_escape_string($dbConn, $_GET["email"]);
$sql = "SELECT * FROM users WHERE email='{$userEmail}' LIMIT 1";// Don't select * if you don't need everything.
$query = mysqli_query($dbConn, $sql);
$pass = $_GET["pass"];// you already have $passwordToCheck.
if ($query) {// Don't need == TRUE
// $row = mysqli_fetch_array($query);
$db_password = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
$username = $row['username'];
echo "$passwordToCheck<br>$db_password<br>";// This is way less verbose than repeating echo and uses less echo functions.
if (password_verify($passwordToCheck, $db_password)) {// Don't need to keep this condition in a variable.
die('ok');// this is just an example to test.
} else {
die('not ok');// this is just an example to test.
}
} else {
header("Location: http://website.com");// While debugging don't redirect, put die('message');
}
$dbConn->close();
?>

mysqli_num_rows return 0 always

here am trying to get username and password from the database and if their result is found then redirect to some page but mysqli_num_rows returns 0 always i dunno why `
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `login` WHERE username = '$username' AND password = '$password'";
$run = mysqli_query($con,$query);
if (mysqli_num_rows($run) == 1) {
header("location: login.php");
}}?>
`
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ornament"; // My local DB Name
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = "test"; // $_POST["username"] value
$password = "test"; // $_POST["password"] value
$sql = "SELECT * FROM `ornament` WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
echo "correct";
} else {
echo "wrong";
}
mysqli_close($conn);
?>
</body>
</html>
OUTPUT:
correct
I have a database name and table name are same, But for me it's working fine.
NOTE: Please check the whether you are using correct password while getting from POST.
Any how you got a solution, Have a great day
Thanks
Muthu

Can't get variables from other php file

I have this code in index.php
<?php
include "ch.php";
?>
ch.php
<?php
if (isset($_POST['Murad'])) {
header("Location: Main.php");
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$userName=$_POST['username'];
$password=$_POST['pwd1'];
$userName = stripslashes($userName);
$password = stripslashes($password);
$userName = mysql_real_escape_string($userName);
$password = mysql_real_escape_string($password);
$email=$_POST['email'];
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "123";
$mysql_databse = "websiteusers";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
$sql = "
INSERT INTO websiteusers
(fullname,lastname,userName,email,pass)
VALUES ( '$firstname', '$lastname','$userName', '$email','$password')
";
mysql_select_db('websiteusers');
$retval = mysql_query( $sql );
if (! $retval ) {
die('Could not enter data: ' . mysql_error());
return false;
} else {
echo "Entered data successfully\n";
}
$usernamecheck=mysql_query("
SELECT `userName` FROM `websiteusers`
WHERE userName='$userName'
");
if (mysql_num_rows($usernamecheck)>=1) {
echo $userName." is already taken";
return false;
}
}
?>
And
Main.PHP
<?php
include 'ch.php';
?>
And
<?php
echo $firstname=$_POST['firstname'];
?>
But it is not working. It worked before I put action in form instead of header but it didn't insert user in database now it inserts but it is not showing variables. Is there anyway to fix this?
1) Do not use mysql_ functions, it's deprecated and will be removed at PHP 7 stable release, choose between mysqli_ or PDO.
2) Don't open and close your php interpreter multiple times with no apparent reason. If your code is pure PHP, a standard is to never close it.
3) There should be nothing else for PHP or HTML to be processed/displayed after using header("Location: ...") function. It's the last thing you do at the script when you use it.

Login page goes directly to the site without checking credentials

I am currently having a problem in which the login page to my website goes directly to the homepage without checking the users credentials stored in my data base. The code I use to register the users works just fine but for some reason I cant get this working properly.
<?php
session_start();
$dbhost = 'localhost:3036';
$dbuser = 'mredd';
$dbpass = 'csc255pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
//mysql_select_db( 'USERS_DB' );
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("USERS_DB",$conn);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$user = $_POST['username'];
$pass = $_POST['password'];
$sql="SELECT * FROM log_tbl Where username='$user' AND password='$pass'";
$retval = mysql_query( $sql, $conn );
$row = mysql_num_rows($retval);
if ($row == 1)
$_SESSION['user'] = $user;
header("Location: homepage.php");
}
?>
Doh! You fell into the trap of not using brackets with your If statement. The final chunk should read
$sql="SELECT * FROM log_tbl Where username='$user' AND password='$pass'";
$retval = mysql_query( $sql, $conn );
$row = mysql_num_rows($retval);
if ($row == 1) { //need this bracket
$_SESSION['user'] = $user;
header("Location: homepage.php");
} //and this one
} // this closes the 'POST' clause
?>
The code you wrote will only set the session if the row is returned, and will ALWAYS redirect to homepage.php. An If statement without brackets only controls the next command.

Basic PHP-script doesn't work

I'm new to PHP and SQL but I'm trying to create a simple PHP-script that allows a user to login to a website. It doesn't work for some reason and I can't see why. Every time I try to login with the correct username & password, I get the error "Wrong Username or Password". The database-name and table-name are correct.
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect("$db_host", "$db_user", "$db_pass") or die("Unable to connect to MySQL.");
mysql_select_db($db_name)or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = ("SELECT * FROM $tbl_name WHERE username='$user' and password='$pass'");
$result= mysql_query($sql);
$count 0= mysql_num_rows($result);
if($count==1){
// Register $user, $pass send the user to "score.php"
session_register("user");
session_register("pass");
header("location:score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if(!session_is_registered(user)){
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
I hope someone can find my mistake, thanks!
FYI session_register and session_is_registered are deprecated and will be removed from PHP. Also try to change your code to use mysqli or PDO. Plenty of articles explain how to do it. Finally, make sure you escape input from the user ($_POST array) because you never know what the user will send and you don't want to be prone to SQL injections. You really do not want to store passwords in clear text, so using SHA1 or MD5 is best.
Having written the above, your code becomes (you can use the $_SESSION global array directly):
connect.php:
<?php
$db_host = 'localhost';
$db_name = 'app';
$db_user = 'root';
$db_pass = '';
$tbl_name = 'users';
// Connect to server and database
mysql_connect($db_host, $db_user, $db_pass) or die("Unable to connect to MySQL.");
mysql_select_db($db_name) or die("Cannot select database.");
// Info sent from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// Protection against MySQL injection
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$sql = "SELECT * FROM $tbl_name "
. "WHERE username = '$user' "
. "AND password = sha1('$pass')";
$result = mysql_query($sql);
// There was an extra 0 here before the equals
$count = mysql_num_rows($result);
if ($count==1)
{
// Register $user, $pass send the user to "score.php"
$_SESSION['user'] = $user;
// You really don't need to store the password unless you use
// it somewhere else
$_SESSION['pass'] = $pass;
header("location: ./score.php");
}
else
{
echo "Wrong Username or Password";
}
?>
score.php:
<?php
session_start();
if (!isset($_SESSION['user']))
{
header("location:login.html");
}
?>
<html>
<body>
<h1>Login Successful</h1>
</body>
</html>
A couple of things
Change this line to the one with error checking i have put below it
$result= mysql_query($sql);
$result= mysql_query($sql) or die(mysql_error());
chances are there is an sql error and you are not picking it up, so the result will always have 0 rows
Also not sure if this line is a typo or not, there shouldn't be a 0 in there
$count 0= mysql_num_rows($result);

Categories