Hey guys ive put together a basic user log in for a secure admin area and it seems to work great, if you enter a correct user/pass you get access, if you enter the wrong user pass, you get no access. However if you enter nothing in both fields you get access.
This is how it works.
Creating a user, a basic form POSTS to this php file.
<?php
$con = mysqli_connect(credentials are all good) or die(mysqli_error($con)) ;
$escapedUser = mysqli_real_escape_string($con, $_POST['user']);
$escapedPass = mysqli_real_escape_string($con, $_POST['pass']);
$some_str = md5(uniqid(mt_rand(), true));
$base_64str = base64_encode($some_str);
$modified_base64 = str_replace('+', '.', $base_64str);
$gensalt = substr($modified_base64, 0, 22);
$format_str = "$2y$10$"; // 2y for Blowfish and 10 times.
$salt = $format_str . $gensalt . "$";
$hashed_pass = crypt($escapedPass, $salt);
$query = "INSERT INTO `userpass` (`username`, `password`, `salt`) VALUES ('$escapedUser', '$hashed_pass', '$salt'); ";
if(isset($escapedUser) && isset($hashed_pass))
{
mysqli_query($con, $query);
header("Location: ausers.php");
exit();
}
Echo "Something went wrong!";
?>
The database appears to be storing these fine
We then log in with this code
<?php
$con = mysqli_connect(again credentials are fine) or die(mysqli_error($con)) ;
$escapedUser = mysqli_real_escape_string($con, $_POST['user']);
$escapedPass = mysqli_real_escape_string($con, $_POST['pass']);
$saltQuery = "select salt from userpass where username = '$escapedUser';";
$result = mysqli_query($con, $saltQuery);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$hashed_pass = crypt($escapedPass, $salt);
if(isset($escapedUser) && isset($hashed_pass))
{
$userQuery = "SELECT * FROM userpass WHERE username='$escapedUser' AND password='$hashed_pass'";
$userpass = mysqli_query($con, $userQuery);
$count = mysqli_num_rows($userpass);
if($count == 1)
{
$_SESSION['username'] = $escapedUser;
header("location: aindex.php");
exit();
}
header("Location: alogin.htm");
exit();
}
Echo "Something went wrong!";
?>
So as i said, this seems to work fine for when any user pass combination is given whether access granted or denied however using no user and pass and pressing log in allows entry. Any ideas? THeres no blank rows in the database table.
Side question, is this salt/hash method correct, its my first attempt.
For your login code, your condition relies on an isset() test. You perform this test on $escapedUser and $hashed_pass. Both of these variables were actually assigned values earlier in the code! Once you assign a value to the variable, it will pass the isset() test, even if the value is an empty string. You might want to use an empty() check, perhaps on the original $_POST variables.
Moving on to the inner condition, which tests if the mysql query returns exactly 1 row of results. If there were truly no rows with empty values, then this condition would never pass because the query would return 0 rows. But it is passing. Two things to consider:
Notice that your registering code uses the same isset() test. Therefore it is very possible that someone used your registration form, submitted empty fields, and successfully registered a row with empty user and password fields. Have you explicitly queried your database for empty fields and actually come up with 0 results?
Your query uses SELECT *. Perhaps this is causing the query to return some sort of aggregate value (like a COUNT() or something that always has a result no matter what). Perhaps try explicitly defining the columns to return?
I cannot comment on your salt/hash method as I have no experience in that part. Hope you find this helpful!
In my opinion you need more than one level of checks in any form, whether it be registration, comments, login, etc. The way I prefer to go about it is a tiered approach. It may work better for you, but it's just an example.
By doing it this way, you ensure that your input will never be empty. Another issue I see with your login script is that you never compare the input with the database so how can you know if they entered the correct information? The only thing allowing them to login is that the query returned a record. This is also why they can login with a blank form.
<?php
$con = mysqli_connect(again credentials are fine) or die(mysqli_error($con)) ;
/* Ensures that form was submitted before any processing is done */
if (isset($_POST)) {
$User = $_POST['user']);
$Pass = $_POST['pass']);
if (!empty($User)) {
if (!empty($Pass)) {
$escapedUser = mysqli_real_escape_string($con, $User);
$escapedPass = mysqli_real_escape_string($con, $Pass);
/* you need to verify the password here, before adding the salt */
$saltQuery = "select salt from userpass where username = '$escapedUser'";
$result = mysqli_query($con, $saltQuery);
$row = mysqli_fetch_assoc($result);
$salt = $row['salt'];
$hashed_pass = crypt($escapedPass, $salt);
$userQuery = "SELECT * FROM userpass WHERE username='$escapedUser' AND password='$hashed_pass'";
/* you need to verify the username somewhere here */
$userpass = mysqli_query($con, $userQuery);
$count = mysqli_num_rows($userpass);
if($count == 1)
{
$_SESSION['username'] = $escapedUser;
header("location: aindex.php");
exit();
} else {
header("Location: alogin.htm");
exit();
}
} else {
echo "Please enter a password.";
}
} else {
echo "Please enter a username.";
}
} else {
echo "You have not entered any information.";
}
?>
Related
So I just learned about storing passwords with MD5 hash and salt in PHP/MySQL. The method I'm using is md5(md5($row["id"].$password)), so the salt is an MD5 hash of the user's ID in my SQL table (which is an auto-incremented INT), which is concatenated to the inputted password string and then re-hashed.
The problem I'm encountering is that when I trying making a test account, and then logging in with the test account, the hash I generate on logging in isn't matching the hash I created when the account was created.
Login Code:
<?php
$login = mysqli_connect("hiding this info for obvious reasons");
if ($_POST["login"])
{
$email = $_POST["email"];
$password = $_POST["passsword"];
$query = "SELECT * FROM useraccs WHERE email='$email'";
if ($result = mysqli_fetch_array(mysqli_query($login,$query)))
{
$hashpass = md5(md5($result["id"]).$password);
if ($hashpass == $result["password"])
{
$errors = "Logged in succesfully.";
}
}
else
{
$error.= "E-mail/Password do not match anything in our database.";
}
}
?>
Register Code:
<?php
$login = mysqli_connect("hiding this info for obvious reasons");
if ($_POST["submit"])
{
$username = $_POST["username"];
$email = $_POST["email"];
$query = "INSERT INTO useraccs (username,email) values('$username','$email')";
mysqli_query($login,$query);
$query = "SELECT id FROM useraccs WHERE username='$username'";
$userid = mysqli_fetch_array(mysqli_query($login,$query))["id"];
$password = md5(md5($userid).$_POST["password"]);
$query = "UPDATE useraccs SET password='$password' WHERE username='$username'";
mysqli_query($login,$query);
}
?>
As you can see, the way I hash the password in both scenarios is identical, and I have done testing to confirm that I am getting the same value for the ID in both scenarios. I am truly stumped as to why I am not getting a match.
I'd like to mention I am very new to using MySQL/creating login systems, so if I've done anything blatantly wrong or have left out essential information, please let me know.
First of all, please see the warnings in the comments, your code is highly unsure.
Regarding the md5: You are using
mysqli_fetch_array(mysqli_query($login,$query))["id"];
This will always return an array. Be sure to get only the field.
The md5 is posting to the database from the signup page so I know that's working, but everything I try here won't let me sign in and just keeps telling me I have the wrong password.
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["user_name"]) ) {
$user = mysql_real_escape_string($_POST["user_name"]);
$pass_word = mysql_real_escape_string(md5($_POST["pass_word"]));
$pass_word=md5($pass_word);
// Connect to the MySQL database
include "../connect_to_mysql.php";
$sql = mysql_query("SELECT m_id FROM member WHERE user_name='$user' AND pass_word='$pass_word' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysql_fetch_array($sql)){
$id = $row["m_id"];
}
$_SESSION["m_id"] = $id;
$_SESSION["user"] = $user;
$_SESSION["pass_word"] = $pass_word;
header("location: ../../index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
You're running MD5 twice on your password.
$pass_word = mysql_real_escape_string(md5($_POST["pass_word"]));
$pass_word = md5($pass_word);
Also, don't use MD5, it is completely unsafe, look into using bcrypt, it is secure, and very easy to implement in PHP. Replacing MD5 with this line of code will make your password hashes safe. Preferably add some salt, the salt being some random string. It will make breaking your passwords nigh impossible.
$hash = password_hash($password . $salt, PASSWORD_BCRYPT);
Change these lines from
$pass_word = mysql_real_escape_string(md5($_POST["pass_word"]));
$pass_word=md5($pass_word);
to
$pass_word=md5($_POST["pass_word"]);
I have a forum page and want a simple login for user with usernames from a predefined mysql user table. I use a login.php form file link from the forum, a get $_POST username, then use a login_handle.php file that calls a function to connect to the DB, query the users array, and try to validate that the $_POST username is in the queried list array.
The function is below, and then the call in login_handle.php I'm getting various errors and don't know if this is at all a good approach. I also want to start a session during the form and verification that can grab the $_POST username as a $_SESSION username and apply to subsequent forum pages.
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users";
$result = mysql_query($query);
$usernames = mysql_fetch_assoc($result);
$isUname = true;
if(!in_array("username", $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
------------------handler call-----------
$username = $_POST["username"];
$password = $_POST["password"];
if(isUsername($username)==true){ // Check if username is valid.
//$Uname = $_SESSION['username'];
//echo "Username = " . $Uname;
echo 'go to forum';
}
First, mysql is deprecated. Please use mysqli.
Second, why don't you use something like...
function isUsername($username){
$query = "SELECT username FROM users WHERE username == '" . $username . "'";
Third: did you search and research?
These kind of question can be easily find everywhere.
As simple as it is , you need to query the specific username from $_POST , not the whole usertable.
I think requesting the number of rows ( number of apparition is a good way to get if user is in database or not , you can make it greater (>=) instead of one user condition (==)).
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users where username='$username'";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
$isUname = true;
if($rows==1) {
$isUname = true;
}else{
echo "Please enter valid user name.<br>";
$isUname = false;
}
return $isUname;
}
I used nearly the same function when I manually assigned a txt array to a variable $username to compare. Now that I am using a user table I merely want to assign the an array of the queried users (thought mysql_fetch_assoc($result) creates the same type of assoc. array) to $username instead of the hard copied elements where it worked with before. Is the array produced with the query different than the $usernames=array("jes34","pes22","jis44","jll124"); that prevents me from doing this?
function isUsername($username){ //Test if proper Username from array.
$usernames=array("jes34","pes22","jis44","jll124");
$isUname = true;
if(!in_array($_POST["username"], $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
-----function call---
if(isUsername($username)==true){ do something }
I'm working on a basic login system. I've used a lot of sources and many places of the code are extracts from other login systems online. The problem is that I am simply and gracefully getting a completely blank page when inputting the username and password into loginpage.html and when it redirects it to this file, BLANK PAGE.
<?php
error_reporting(E_ALL ^ E_NOTICE);
include 'connectingshit.php';
//Basically naming a session and starting one
session_name('litLogin');
//The cookie is going to live for 2 weeks
session_set_cookie_params(2*7*24*60*60);
//Now we actually start the session
session_start();
ob_start();
if($_SESSION['id'] && !isset($_COOKIE['RemainLoggedIn']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the cookie (browser restarts)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_POST['submit']))
{
//I hope I know what I am doing, this is supposed to hold our errors.
$errors = array();
if(!$_POST['username'] || !$_POST['password'])
$errors[] = 'All the fields must be filled in buddyboy!';
if(!count($errors))
{
//Assigning the input form shit to the variables/strings or wtf they are
$tinkerbells_username = $_POST['username'];
$tinkerbells_password = $_POST['password'];
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// We remove all dangerous characters (!!!!) WTF? Escaping them "WOW"...
$tinkerbells_username = stripslashes($tinkerbells_username);
$tinkerbells_password = stripslashes($tinkerbells_password);
$tinkerbells_username = mysqli_real_escape_string($conn, $tinkerbells_username);
$tinkerbells_password = mysqli_real_escape_string($conn, $tinkerbells_password);
$row = mysqli_fetch_assoc('SELECT id, username, password FROM members WHERE username = "$niloquieroser_username" AND password = "$niloquieroser_password"');
//Does basically the username exist when $row lookes for it in the database
if(($row['username']) && ($niloquieroser_username == $tinkerbells_username && $niloquieroser_password == $tinkerbells_password))
{
//Now fortunately or unfortunatley if it did work and everything is fine
//We can continue.....
$_SESSION['username'] = $row['username'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
//We store some data in the session
setcookie('RemainLoggedIn',$_POST['rememberMe']);
//cookie gets created
}
else $errors[]=("Wrongs username or/and password!");
}
header("Location: success.html");
exit;
}
ob_end_flush();
?>
$row = mysqli_fetch_assoc('SELECT id, username, password FROM members WHERE username = "$niloquieroser_username" AND password = "$niloquieroser_password"');
MySQL strings should be single-quoted; you're calling mysqli_fetch_assoc on a string, not a query object; your variables won't be interpolated, since the PHP string uses single quotes. Not that you should interpolate them anyway; use prepared statements.
Also, please hash your darn passwords.
First of all, fix your query. You can't embed php values in strings without define your strings with double quotes:
$query = "SELECT id, username, password FROM members WHERE username = '$niloquieroser_username' AND password = '$niloquieroser_password'";
You want to use mysqli_query() to get a mysqli_result set. Then you can loop through that like so:
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
//echo $row['username'];
...
}
If you manage to get your script working properly, note that it seems like even if the username/password was invalid, you still redirect them to success.html. You should put header("Location: success.html"); inside the if that checks the result set for a row only, and echo the error message if the row was not found.
So recently I learned how to properly add a username and password to a database.
My database is usersys, and the table storing user information is called userdb. The table has two columns - username (primary), password.
The registration form works great, enters the users input into the database correctly and also checks to see whether the user's username is already in the database or not.
With that said, I am asking if anyone could help me create a login script. So far, this is what I have:
$username = $_POST['username'];
$password = $_POST['password'];
$displayname = $_POST['username'];
$displayname = strtolower($displayname);
$displayname = ucfirst($displayname);
echo "Your username: " . $displayname . "<br />";
mysql_connect("localhost", "root", "******") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("usersys") or die(mysql_error());
echo "Connected to Database <br />";
$lcusername = strtolower($username);
$esclcusername = mysql_real_escape_string($lcusername);
$escpassword = mysql_real_escape_string($password);
$result = mysql_query("SELECT * FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$validateUser = $row['username'];
$validatePass = $row['password'];
The POST data is from the previous log in page. I want this script to check the table (userdb) and find the row for the username that the user entered from the previous form and verify that the password entered matches the username's password set in that row, in userdb table.
I also want some type of way to check whether or not if the username entered exists, to tell the user that the username entered does not exists if it can not be found in the table.
This is not a direct answer to this question but a GOOD value-add.
You should use MYSQL SHA1 function to encrypt the password before storing into the database.
$user = $_POST['userid'];
$pwd = $_POST['password'];
$insert_sql = "INSERT into USER(userid, password) VALUES($user, SHA1($pwd))";
$select_sql = "SELECT * FROM USER WHERE userid=$user AND password=SHA1($pwd))";
You can use sessions. Sessions are global variables that when set, stay with the user while he is browsing through the site.
Since you are learning PHP, try out this tutorial on the official website.
But what you would do in theory is when the username and password match, you set a session variable
$_SESSION["auth"] = true;
$_SESSION["user_id"] = $row["user_id"];
And then do a check to see if the user is authenticated.
One way to do it (DISCLAIMER: not necessarily best-practice):
$result = mysql_query("SELECT id FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$id = (int)$row['id'];
if($id > 0) {
//log in the user
session_start();
$_SESSION['userId'] = $id;
$_SESSION['username'] = $displayname;
}
... and on pages that require authentication:
session_start();
if(!isset($_SESSION['userId'])) {
die('You need to be logged in!!!');
} else {
echo 'Welcome ' . $_SESSION['username'];
}
Read more about PHP sessions.
I like to use both $_SESSION and MYSQL Checks with any login POST. This should help get a few things started.
$username = mysql_real_escape_string($_POST[username]);
$password = strip_tags($_POST[password]);
$password = sha1($password);
if(isset($username) && isset($password) && !empty($username) && !empty($password))
{
$sql = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
//Check the number of users against database
//with the given criteria. We're looking for 1 so
//adding > 0 (greater than zero does the trick).
$num_rows = mysql_num_rows($sql);
if($num_rows > 0){
//Lets grab and create a variable from the DB to register
//the user's session with.
$gid = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
$row = mysql_fetch_assoc($gid);
$uid = $row[userid];
// This is where we register the session.
$_SESSION[valid_user] = $uid;
//Send the user to the member page. The userid is what the
//session include runs against.
header('Location: memberpage.php?userid='.$userid);
}
//If it doesn't check out -- throw an error.
else
{
echo 'Invalid Login Information';
}
}
NOTE: You would need to start the page file with session_start() and create a separate Session Check include stating with session_start() and then your progressions e.g. if($_SESSION[valid_user] != $userid) do something.
You could use a select statement to retreive from MySQL the password for the specified username. If you have an empty result set, then you do not have the username in the table.
If you need the user to be authenticated in more than one php page, then one choice whould be using sessions (http://www.php.net/manual/en/function.session-start.php).
Also, I think you should think about security, i.e. preventing SQL injection:
$variable = mysql_real_escape_string($_POST['variable'])
and avoiding to "die" (treating errors and returning user-friendly messages from the script).
I would also think about not storing passwords in your database. One way hashes with MD5 or SHA1 are a way of adding a layer of security at the db level.
See http://php.net/md5 or http://php.net/sha1 for further information.
I agree with the idea if using SESSION variables while authenticating the user.
The easy way to authenticate the user is as follows
//connect the mysql_db
$mysql_connect()
$mysql_select_db()
//reading from mysql table
$res="SELECT * FROM table WHERE name=$username AND password=$password";
$val=mysql_query($res);
//authentication
$count=mysql_num_rows($val);
if($count==1)
//authenticate the user
else
through an error