I am creating a simple PHP login system using SQLite, when when the user posts the the HTML form, the system guides them to the "members only page" regardless of what they entered. Here is my form processing code:
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$database = new PDO("sqlite:database.sqlite");
$result = $database -> query("SELECT COUNT (*) FROM accounts WHERE username = '$username' AND password = '$password'");
if ($result > 0)
{
setcookie("session", "Cool", time()+3600);
header("location:index.php");
}
else
{
echo "Failure";
}
?>
Help!
I think it should be...
if ($result->rowCount() > 0) ...
AND: use prepared statements to avoid SQL-injection, don't store uncrypted passwords in your DB, it's a huge security-problem.
Try this (You shouldn't need count, just a simple logical statement):
$query = "SELECT * FROM accounts WHERE username = :username AND password = :password";
$stmt = $database->prepare($query);
$stmt->execute(array(":username"=>$username, "password"=>$password));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
//Success
setcookie("session", "Cool", time()+3600);
header("location:index.php");
}
// Not successful.
return null;
Related
I am trying to create a login.php script which uses password_verify() encryption. None of the topics were clear and the problem is that in every example it looks like this
$password = '123';
$hashed = '$2y$10$Lz6eWEzHqhNhiPkNYX/LAOfP.1zuyYJSc4u66TvF1bce9WrSbnSJK';
$ver_pass = password_verify($password, $hashed){..}
Now for me the thing is that i am trying to retrieve the hashed password from a database and not from an internal hardcoded string.
My sample code:
login.php
$password = mysqli_real_escape_string($database, $password);
//Check username and password from database
$query =
"SELECT id FROM `register`
WHERE `username` = '$username'
AND `hashed_p` = '$password'";
$result = mysqli_query($database,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
$verified_password = password_verify($password, $hashed_password);
if(mysqli_num_rows($result) && $verified_password){
echo start session succesfully
}else{ echo error}
}
register.php
$password = mysqli_real_escape_string($database, $password);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = "SELECT email FROM register WHERE email='$email'";
$result = mysqli_query($database, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$query = mysqli_query($database,
"INSERT INTO `register` (`hashed_p`) VALUES ('".$hashed_password."')";
if ($query) {....}
By the way. The registration process is successful and the password_hash() works fine in the register.php file.
But in the login.php file I don't know how to retrieve the hashed password from the database and use it to verify it.
You need to Select id & password without checking for password. Then you check if the pwdHash from db ($row['hashed_p']) matches the one the user gave via password_verify:
$password = // the password in it's raw form how the user typed it. like $_POST['password'];
//Check username (without password) from database
$query =
"SELECT id, hashed_p FROM `register`
WHERE `username` = '$username'";
$result = mysqli_query($database,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$verified_password = password_verify($password, $row['hashed_p']);
if(mysqli_num_rows($result) && $verified_password){
echo 'start session succesfully';
} else {
echo 'error';
}
BUT please change to a prepared statements (because your version is very unsecure. could easily be hacked. Just seach for 'Bobby Tables'.):
$stmt = mysqli_prepare($database, $query);
mysqli_stmt_bind_param ($stmt, 's', $username);
$success = mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
I've put username and md5(password) on my MySQL database. Below is my old login PHP code. I want to add some code that can retrieve my md5 password, because on my old code there is no md5 password. Where is should I add md5(password)?
Here is my full login code:
<?
if ($_POST['username']) {
$username=trim($_POST['username']);
$username = mysql_real_escape_string($username);
$password=trim($_POST['password']);
$password=mysql_real_escape_string($password);
//$password = hash('md5','$password');
if ($password==NULL) {
header("Location: login.php?error=2");
}else{
if($_POST['code']!=$_SESSION['string']){
header("Location: login.php?error=1");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
header("Location: login.php?error=3");
} else {
$data = mysql_fetch_array($query);
if($data['password'] != $password) {
header("Location: login.php?error=4");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username='$username' ") or die(mysql_error());
$row = mysql_fetch_array($query);
$nicke=$row['username'];
$passe=$row['password'];
setcookie("usNick",$nicke,time()+36000);
setcookie("usPass",$passe,time()+36000);
$lastlogdate=time();
$lastip = getRealIP();
$querybt = "UPDATE tb_users SET lastlogdate='$lastlogdate', lastiplog='$lastip' WHERE username='$nicke'";
mysql_query($querybt) or die(mysql_error());
$query = mysql_query("SELECT akhirupgrade from tb_upgrade WHERE username = '$username' and status='upgraded'") or die(mysql_error());
if(mysql_num_rows($query) > 0) {
$row = mysql_fetch_array($query);
$akhir=$row["akhirupgrade"];
$tgl=time();
if ($tgl > $akhir) {
$query = mysql_query("update tb_upgrade set status='', date='', paket='', akhirupgrade='' WHERE username='$username' and status='upgraded'");
$query = mysql_query("update tb_users set account='' WHERE username='$username'");
}
}
header("Location: member.php");
}
}
}
}
}
?>
I would use password_hash() if you running on php 5.5 or greater
When you send the password to the database simply hash it with the function
$password = password_hash(filter_input(INPUT_POST, "password"));
The when you pull the password back out of the database do the same thing to the password they submitted.
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = password_hash(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}
I have not tested this code so there may be errors but hopefully youll get the point :)
PS dont use MD5 please, Very insecure
If you must use md5
$password = md5(filter_input(INPUT_POST, "password"));//Store password
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = md5(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}
I've created a below script, which is intentionally not secure, in order to learn a bit more about cyber security.
session_start();
if($_SESSION['userSession']) {
header("location: home.php");
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
$con = mysqli_connect("localhost", "myUsername", "myPassword", "myDatabase");
if(!$con) {
die("Error: " . mysqli_connect_error());
}
$query = "SELECT * FROM users WHERE username = '$username' && password='$password'";
$result = mysqli_query($con, $query);
$numResults = mysqli_num_rows($result);
if($numResults == 1) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['userSession'] = $row['id'];
header("location: home.php");
} else {
echo "Error Logging In";
}
mysqli_close($con);
}
As you can see, I have not escaped the user input and the password has not been hashed.
Therefore, I am presuming that this should be an easily hackable login. However, I have attempted to use the below input in both of the username and password fields, but always get the output "Error Logging In".
password' OR '1' = '1'";
How can I try to bypass/hack my login script?
If we use sql statement directly to fetch username and password field then it can be bypass with ' OR '1' = '1 pattern, because when you put ' OR '1' = '1 in username and password field that values carry forward to sql statement and in that statement ' or '1' = '1 is true for all the cases and that's a reason login can bypass.
I can't get this to work. I am new to working with prepared statements so i i'm kinda 50/50 on what i'm doing.
Upon registration, the password is hashed with password_hash($pass,PASSWORD_DEFAULT)
Now, i'm trying to get my login page to function with this but i dont know where / how to write it with the password_verify()
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE BINARY username=? AND password=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("ss",$username,$password);
$stmt->execute();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
if($num_rows == 1){
$rows = $result->fetch_assoc();
if(password_verify($password, $rows['password'])){
$_SESSION['loggedin'] = $username;
$_SESSION['country'] = $rows['country'];
$_SESSION['email'] = $rows['email'];
$_SESSION['avatar'] = $rows['u_avatar'];
$_SESSION['is_gm'] = $rows['is_gm'];
$_SESSION['user_lvl'] = $rows['user_lvl'];
$_SESSION['totalposts'] = $rows['post_total'];
$_SESSION['totalcoins'] = $rows['coins_total'];
$_SESSION['totalvotes'] = $rows['vote_total'];
$_SESSION['secquest'] = $rows['sec_quest'];
$_SESSION['secanswer'] = $rows['sec_answer'];
$_SESSION['join_date'] = $rows['join_date'];
header("Location: /index.php");
exit();
}
} else {
echo "<p class='error_msg'>No accounts could be found with the given credentials.</p>";
}
$stmt->free_result();
$stmt->close();
$db->close();
I would assume that the password verify would before if($num_rows == 1) but as i said, i have no idea.
Your query is essentially:
SELECT * FROM users WHERE username=username AND password_hash=plain_text_password
This isn't going to work. If you're relying on PHP password hashing, you can't do a password comparison on the SQL level. Retrieve the password hash from the database then do the password_verify (exclude the password=?) in your WHERE arguments.
I made a simple social network system, with register and login function, but whem the user register and try to login, he give this message:
Fatal error: Call to a member function rowcount() on a non-object in home/login.php on line 7
I'm using PDO connection.
There is some problem in my login.php code?:
<?php
include('dbcon.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = $conn->query("select * from database where username = '$username' and password = '$password'");
$count = $query->rowcount();
$row = $query->fetch();
if ($count > 0){
session_start();
$_SESSION['id'] = $row['member_id'];
header('location:home.php');
}else{
header('location:index.php');
}
?>
I am assuming you are using PDO, and the rowcount method does not exist, but on the other hand there is a rowCount method. Remember these are case-sensitive.
<?php
include('dbcon.php');
$username = $_POST['username'];
$password = $_POST['password'];
$stm = $conn->prepare("select * from database where username = ? and password = ?");
$stm->execute(array($username, $password));
$count = $stm->rowCount();
$row = $stm->fetch(PDO::FETCH_ASSOC);
if ($count > 0) {
session_start();
$_SESSION['id'] = $row['member_id'];
header('location:home.php');
} else {
header('location:index.php');
}
?>
This should do the trick.
PDOStatement::rowCount
I also edited your query, so that it uses a prepared statement with placeholders, this will protect you from SQL Injection.
Assuming that your table is actually called database, you should note that it is a reserved word, and should be protected by backticks.
Additionally, as mentioned above, method names are case-sensitive, so you should call rowCount() and not rowcount():
$query = $conn->query("select * from `database` where username = '$username' and password = '$password'");
$count = $query->rowCount();