Prevent users from having the same username - php

I have just found a pretty major vulnerability in my code while doing some testing,
Basically if my username was "admin" and password was say "12345"...
and a user joined with and chose the name "Admin" and the same password "12345"
when he/she goes to login they will be in my account on the website, As you can imagine I have created quite a flaw, as this would affect every potential user on the site.
So, my question is what can I change in this statement to make it check for an EXACT match.
WHERE login_name ='$user' AND user_password ='$pass' LIMIT 1";
Heres the login_process.php file
<?php
require_once("includes/session.php");
$connection = mysql_connect("localhost", "user", "password");
if(!$connection)
{
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("game", $connection);
if(!$db_select)
{
die("Database selection failed: " . mysql_error());
}
$user = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);
$pass = sha1($pass);
// Need to make a change to the below query, as it doesn't match for case sensitivity.
$query = "SELECT user_id, user_name, user_level FROM users WHERE login_name ='$user' AND user_password ='$pass' LIMIT 1";
$result=mysql_query($query);
if(mysql_num_rows($result) == 1)
{
$found_user = mysql_fetch_array($result);
$_SESSION['user_id'] = $found_user['user_id'];
$_SESSION['user_name'] = $found_user['user_name'];
$_SESSION['user_level'] = $found_user['user_level'];
header("Location: index.php");
}
else
{
echo "The username or password you entered was incorrect. <br/> Please click <a href='login.php'>Here</a> to try again.";
}
?>

the default collation of database is case insensitive . so the user admin and Admin or adMin are the same. While creating user check the database whether same username already exist or not.
it seems that you are using case sensitive collation.. you can use case insensitive collation for that user table so that your query will work fine.
or
while creating user and checking the database for duplicate entry use LCASE function as follows
SELECT * FROM USERS WHERE LCASE(username) = 'admin'

You should have a UNIQUE constraint on your login_name column:
alter table users add constraint unique (login_name)
That should take care of any new entries that are added that only differ from existing entries by case (assuming of course that you're using the default case insensitive collations). If you get complaints like
ERROR 1062 (23000): Duplicate entry 'XXX' for key 'login_name'
then you already have duplicates and you'll need to clean those up before adding your UNIQUE constraint.

Related

search for existing user in database PHP

I'm trying to take input from form and compare to $username in database.
If the username does not exist it should print error.
elseif (($_POST['user']) != ($this->mysqli->query("SELECT * FROM users WHERE username='" . $username . "'"))) {
$json['message'] = "User does not exist";
}
This doesn't log a php error, but it doesn't work either.
Make sure you're receiving the correct username through the POST request, this is a common source of errors. Just log it and check the errors file.
Then, let's analyze your mysql query:
SELECT * FROM users WHERE ...
After the select keyword, you should specify which columns you want to be returned. An asterisk (*) means you want all of them, which is fine if you have a single column, the username, but I'm assuming you have more. In this case, notice in your code that you'll be comparing a bunch of columns against the username. It will fail.
Check out this tutorial, it will be helpful to get familiar with using php plus mysql.
I wrapped the snippet below to show you a way of doing this, there are many. It is just checking if the query returned zero rows, which indicates that no record with the given username exists. A better way would be using the mysql function EXISTS().
$username = $_POST["username"];
error_log("Checking if username:'$username' exists.", 0);
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
$sql = "SELECT * FROM users WHERE username = '$username'";
$query = $conn->query($sql);
if ($query->num_rows == 0) {
error_log("The username does not exist.", 0);
}

How can I verify a form with an SQL databse?

So I have an SQL database that has a table for accounts and info, and another one for storing comments on articles. I Have a form for submitting comments and it works just fine, but I wanted to implement a feature to prevent spam and non registered accounts. I was trying to find a way to make the following code work so that it would call upon my account table and check to see if the username section matches what was entered in the form.
I want it to check through my username column on the table to see if what was entered in the box is actually in the database as well, that way if it hasn't been registered it won't submit.
My problem I keep running into is that I try this
<?
if ($_POST['Uname']==`username`){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
But when I do this it thinks that "username" is what the username needs to be in order to submit properly.
I do not want every username to need to be "username" in order for them to submit, I just want it to check through my username column to see if what was entered is one of the registered usernames in the SQL column.
Im not sure if this is possible, or if I am making any sense, but this is my first post on this site and I would appreciate any help I could get.
Full code is below
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("sql***.*******.com","*****","*******");
$db_selected = mysql_select_db("*********",$con); //My login
$test2=$_GET['ID']; //Ignore
$_POST['#']=$test2; //Ignore
$sql="Select * from `Articles` and `Accounts`"; //For pulling data
mysql_query($strSQL,$con);
if ( ? == ? ){ //What should go here?
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Edit
So after making the changes needed, should my previous code end up like this?
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("*******","********","*****");
$db_selected = mysql_select_db("*****",$con);
$test2=$_GET['ID'];
$_POST['#']=$test2;
$username = $_POST['Uname'];
$sql = "Select `id` from `Accounts` where `username` = $username";
mysqli_num_rows($sql,$result);
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
echo $result;
if ($row_cnt!=''){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES ('".$_POST['Uname']."',
'".$_POST['Comment']."',
'".$_POST['Date']."',
'".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Obviously what you doing is not correct, as of now you are putting condition as :
if ($_POST['Uname']==`username`)
which means you saying any user who's name is 'username' should be able to comment, but what you want to achieve is, any user who is valid user and is exist in db should be able to comment. So for that you should write a select sql to check the user, :
$username = $_POST['Uname'];
$sql = "select id from yourusertable where username = $username";
then,
perform
mysqli_num_rows
to check if you get anything greater than zero. If yes, then allow to submit comments.
Simply apply the check that only loggedIn user can comment. So if the user will not exist in users table it will not be loggedIn nor can comment.

Unable to fetch and compare mysql data in php

I want to check if the 'desig' (designation) of a user stored in user_info database, is 'gm' (G.M.) or not.
Currently, I have two users, one with 'desig' as 'gm' and the other as 'mgr', no matter who logs in, the 'gm.html' page always loads.
The correct working should be that if the desig is gm then only it should redirect to gm.html page. (members is a table in user_info db)
<?php
session_start();
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {echo "";}
else{
header("location:login.html");}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$desig = mysqli_fetch_array($result) or die("error");
if($desig!="gm")
{
$mysql_db1='customer';
$con1=mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db1) or die("Connection died for your sins.");
echo "Connected";}
else
header("location:gm.html");
?>
Your code seems to be hard-coded to only return a GM?
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
I am pretty sure that this is supposed to be picked up based on the user and not simply running a "find me a GM user" for anyone.
If I understand your question correctly, shouldn't there be somewhere in betwen the start and end of this snipped that uses the login information to verify what level a user is it?
if((isset($_SESSION['login']) && $_SESSION['login'] ==true))
{
echo "";
// Shouldn't you run a query here to see who your user is?
// For example to get their ID?
}
else
{
header("location:login.html");
}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
// Then here, instead of running this, convert it to something similar to:
$result = mysqli_query($con, "SELECT desig FROM members WHERE userid=$id");
Edit:
Storing the variable is easy - but you have to GET it from somewhere.
You can do this by popping a column in your users table - where you verify the username and password to begin with. I would suggest you look into a basic table like this to store user information. (I would also recommend you store hashes of passwords and the like, but that seems a conversation for another time).
user table:
userID username password userLevel
1 someUser somePass Grunt
2 someUser1 somePass1 MGR
3 someUser2 somePass2 MGR
4 someUser3 somePass3 GM
Armed with this, you can fire off a quick query to the database, verify the username and password, and get their userLevel quite easily.
Once you have the level, you can store it in a session variable if you like and have your code apply logic depending on what is stored in there.
I fixed the problem. There were some logical errors in my code.
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {
//Selecting the whole row to compare and display different variables
$sql = "SELECT * FROM members WHERE username = '".$_SESSION['username']."'";
if(!$sql)
echo mysql_error();
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//Using $row variable to fetch and compare the value stored in 'desig' with 'gm'
if($row["desig"]=='gm')
header("location:gm.php"); //Opens up different page for gm aka Gen. Mgr.
}
else
header("location:login.html"); //Redirects to this page if no user is logged in.

Redirect to a different page based on role in a database

I'm new to PHP. I'm trying to create a login page that will redirect to different pages based on their roles. they will login with staff id and password.
Below are my database
Staff_id password Role
XXX XXX XXX
My HTML login page ---> Login.html
My php code for login --> Login2.php
I've seen other questions n solutions but I still can't get it right. When I log in, it just direct me to an empty page -xx/xx/Login2.php'. What did I do wrong?
I'm using PHP 5.**.
These are my php code:
// Connect to server and select databse.
$db= new mysqli("$host", "$username", "$password");
//check connection
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
// username and password sent from form
$staff_id=$_POST['staff_id'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$staff_id = stripslashes($staff_id);
$password = stripslashes($password);
$staff_id = mysql_real_escape_string($staff_id);
$password = mysql_real_escape_string($password);
$sql="SELECT ROLE FROM $tbl_name WHERE STAFF_ID=$staff_id and PASSWORD='$password'";
$rslt= $db -> query($sql);
// Mysql_num_row is counting table row
$count= $db -> affected_rows;
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$row = mysqli_fetch_array($rslt, MYSQLI_ASSOC);
switch($row["ROLE"])
{
case 'ADMIN':
header("location: /test/HTMLPages/Admin-register.html");
break;
case 'MANAGER':
header("location: /test/HTMLPages/View-report.html");
break;
default:
echo "Wrong staff ID or password";
}
}
?>
Know that I take others code and patch it up as logically as I can.
EDIT: Fixed. of course it would go nowhere because i didn't state the database name. :D
thank u for ur time :D
you select ROLE but as you saied you wrote Role in the DB, you need to write the SAME way you wrote the atrr in the table, and like Fred saied in the comments, it goes the same way in the $row['Role']
switch($row["Role"]){
}
$sql="SELECT Role FROM {$tbl_name} WHERE STAFF_ID={$staff_id} and PASSWORD={$password}";
i dont know if you not included $tbl_name, but from the code above it seems like you have no $tbl_name variable

MySQL Check if username and password matches in Database [duplicate]

This question already has answers here:
How to check username and password matches the database values
(3 answers)
Closed 11 months ago.
I have a form which has a textbox with the name attribute username and another one with the name attribute password.
I also have a database with columns called user and pass. When my users signed up it added the username to the user column and password to the pass column.
How would I make a MySQL query to check if the form submitted the right username and password and then if it did have a branch to let me input the code for if it succeeded?
I really need some code, this bit isn't going well I know it should be something like SELECT * FROM table WHERE username == $username AND... but then I'm stuck because I have an MD5 password in the database and that first bit is probably wrong. Please help. :)
Thanks
//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);
if ($user&&$pass)
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
//while loop
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
else
die("incorrect username/password!");
}
else
echo "user does not exist!";
}
else
die("please enter a username and password!");
Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).
You can limit the whole search to one row by using Limit 0,1
SELECT COUNT(UserName)
FROM TableName
WHERE UserName = 'User' AND
Password = 'Pass'
LIMIT 0, 1
1.) Storage of database passwords
Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.
2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.
The query should then look like this:
select hashedPassword from users where username=?
Then compare the password to the input.
Further questions?

Categories