Check if a username already exists [duplicate] - php

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 6 years ago.
I want to check if a user already exists.
I made the following code but it is not working.
The echo in the checkUser is only to look if it jumps in the if clause.
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$checkUserID = mysql_query("SELECT *
FROM users
WHERE username = '$username'");
if (mysql_num_rows($checkUserID) >= 1) {
//echo "User id exists already.";
echo "testststst";
$user1 = mysql_fetch_array($checkUserId);
$result = flashMessage("User is already taken, please try another one");
//print_r($user); // the data returned from the query
}else if(empty($form_errors)){
...formcheck...
}
I hope somebody can help me I don't know what to do.

I suggest you tu use PDO library. For your problem the best solution is to have the username in the table as PRIMATY KEY or with a UNIQUE CONSTRAINT. This way, if you try to insert two times the same username, the query will throw an exception (or will return false depending how you set it) and it's easier to do.

I can see the following problems with your code--
You haven't made any database connection.
You should check whether the $_POST variables are available or not. That is try to use if(isset) function to check it.
Try using prepared statements as they are more secure.

first of all ur code is vulnerable to sql injections. Wrapped the form data with the function.
<?php
//function to prevent sql injections
function validateFormData($formData) {
$formData = trim( stripslashes( htmlspecialchars( strip_tags( str_replace( array( '(', ')' ), '', $formData ) ), ENT_QUOTES ) ) );
return $formData;
}
$email = validateFormData($_POST['email']);
$username = validateFormData($_POST['username']);
$password = validateFormData($_POST['password']);
$checkUserID = mysql_query("SELECT *
FROM users
WHERE username = '$username'");
if (mysql_num_rows($checkUserID) >= 1) {
//echo "User id exists already.";
echo "testststst";
while ($row = mysqli_fetch_assoc($checkUserID)){
//set some variables to save some data
$usernameD = $row['username'];
}
//compare form username with db username{
if($usernameD === $username){
echo "Username already taken";
}else{
//continue the rest...
}
}
?>

Related

how to disable user account php/mysql

I am trying to have user accounts that can be enabled or disabled.
I have a active field in my table that is set to either yes or no.
This is my code for the login page.
<?php
/* User login process, checks if user exists and password is correct */
require_once 'includes/db.php';
// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM dxd_membership WHERE email='$email'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
$active = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '$email' AND active = 'YES'");
if ($active == '1')
{
if ( password_verify($_POST['password'], $user['password']) ) {
$userid = $_SESSION['userid'];
$_SESSION['email'] = $user['email'];
$_SESSION['firstname'] = $user['firstname'];
$_SESSION['lastname'] = $user['lastname'];
$_SESSION['username'] = $user['username'];
$_SESSION['paynum'] = $user['paynum'];
$_SESSION['empnum'] = $user['empnum'];
$_SESSION['phone'] = $user['phone'];
$_SESSION['active'] = $user['active'];
$_SESSION['lastlogin'] = $user['lastlogin'];
$_SESSION['signup'] = $user['signup'];
$_SESSION['lastupdate'] = $user['lastupdate'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
$update = $mysqli->query("UPDATE dxd_membership SET lastlogin=NOW() WHERE email = '$email'");
header("location: welcome.php");
}
else {
$_SESSION['message'] = "You have entered wrong password please try again!";
header("location: error.php");
}
}
else {
header("location: disabled.php");
}
}
?>
I am sure it is a silly error i have here but it will not check the active field and then either let the user login to the welcome.php page if active is yes or send them to the disabled.php page if their account active is set to no (disabled).
Can anyone help me with correcting the code so that it will work.
Thanks
Look, I see several issues in your code. The first is the double query for the same data. You can simplify this whole thing to one query.
Another (and more important) is the fact that you're just appending data to the SQL query, where the whole objective of MySQLi is to avoid injections by binding params. So a -more- correct way to do it would be this one:
EDIT: escape_string avoids this. I completely ignored it.
<?php
/* User login process, checks if user exists and password is correct */
require_once 'includes/db.php';
// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '{$email}'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("Location: error.php");
exit; // Add an "exit" here, because if you add something else, it will run too (even if you asked to redirect... basically is the browser the one that chooses if it follows the redirect or not, but your script still goes on).
}
else { // User exists
$user = $result->fetch_assoc();
// There's no point in filtering using another MySQL query, since YOU ALREADY HAVE THIS DATA. Just use PHP to read it and act appropiately.
// Doing another query is just WASTING resources for no useful purpose.
//$active = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '$email' AND active = 'YES'");
if ( $user['active'] == 'YES' ) {
// Your processing here, you get the idea
}
}
?>
Of course, the best alternative is to use a MySQLi statement and use bind_param/execute. This example is only to follow your style of using MySQLi.
It's pretty obvious
$active = $mysqli->query("SELECT * FROM dxd_membership WHERE email = '$email' AND active = 'YES'");
if ($active == '1') //<-- see it
{
if ( password_verify($_POST['password'], $user['password']) )
Try this
if ($active->num_rows == 1 ) //or != 0 This is false or a result set.
Even if you did have the value of their active filed in there ( you have select * ) you would still be checking string '1' against string 'YES'
Please note I haven't used mysqli in about 4 years, as I use PDO. So that might not be the entire problem, but just seemed wrong..
In fact that second query is not needed as you already have the data you seek, so you can change it.
Now if you are sure active will always be YES for them being active, the $user already contains this data, so why not use it like this, and save the query.
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM dxd_membership WHERE email='$email'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error.php");
}else { // User exists
$user = $result->fetch_assoc();
/* comment these next 2 lines out when not debugging */
echo "<pre>"; //whitespace formating
var_export( $user );
if ($user['active'] == 'YES'){
// .....
}
}
One thing I feel compelled to mention is that you should look into prepared statements. You can find information on that here
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Whenever you concatenate in a SQL query you should be using a prepared statement instead, as it opens you application to SQL injection attacks. Now that I look closer you are using escape_string while this is good, the preferred way is prepared statements. This is because with a prepared statement, the variables are entirely separate from the query commands and so the DB knows not to execute anything in them. Even with escaping there could be edge cases that may be an issue, I don't know of any per-say, but something like using a Hexadecimal version of a quote are things I have seen in examples, or weird character strings that the DB would see as a quote.

Fetch results from prepared SELECT statement [duplicate]

This question already has answers here:
MySQL password function
(4 answers)
Closed 2 years ago.
I am making a php document the logs the user in if they are in the database and entered the correct username and password. To be secure I am using prepared statements but I can't get the results from my SELECT query to set session variables necessary for my site. Here is my code...
<?php
session_start();
require 'config.php'; #This file has all connection info
#$C is the mysqli connection
#$USERS is the name of the table in my database
$sql = $C->prepare('SELECT ID,Username,Favorites FROM '.$USERS.' WHERE Email=? AND Password=PASSWORD(?)');
$sql->bind_param("ss", $e,$p);
$e = $_POST['e'];#email
$p = $_POST['p'];#password
$query = $sql->execute();
$sql->store_result();
$numrows = $sql->num_rows;
if($numrows == 1) {
$sql->bind_result($id,$username,$favs);
while($sql->fetch()) {
$_SESSION['ID'] = $id;
$_SESSION['Name'] = $username;
$_SESSION['favs'] = $favs;
$_SESSION['valid'] = true;
}
echo 'true';
}
else {
echo 'User Not Found';
}
This just echoes 'User Not Found' because $numrows always = 0 and I made sure that all the entered info was correct.
Move the variable assignments to $e and $p above the call to bind_params or at least declare them above the call.
The parameters to bind_params are passed by reference, so changes to the variables after bind but before execute take effect, but AFAIK the variables have to exist before the bind call.

How do I pass in a variable with an exclamation mark in it? PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm working on a database login system in PHP but one of my users has an exclamation mark in his password which breaks it, The line where it says ($password = $_GET['p'];) is where the password gets passed in
$username = $_GET['u'];
$password = $_GET["p"];
function userLoginIpb($username, $password) { //select the password information froms elected user
$query = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT `members_pass_salt`, `members_pass_hash` FROM `members` WHERE `name` = '$username'");
$results = mysqli_fetch_assoc($query);
$password = md5(md5($results['members_pass_salt']).md5($password));
if ($password == $results['members_pass_hash']) {
return true;
} else {
return false;
}
The issue is your $_GET[] request, since a ! character will be encoded to %21.
Since you're working on the system, do it the correct way instead.
Use POST requests, as you don't want the users to copy paste a link with a password in them.
Use the new functions in PHP, password_hash() with password_verify() as they have a salt build into them making it quite secure and very easy to work with.
Bind values to a SQL string do not blindly put them in there as you are currently open to an easy SQL injection. Adding a password like pass; DROP TABLE members; will break it.
You need to use mysqli_real_escape_string:
<?php
$username = $_GET['u'];
$password = $_GET["p"];
// select the password information froms elected user
function userLoginIpb($username, $password)
{
global $___mysqli_ston;
$s = mysqli_real_escape_string($___mysqli_ston, $username);
$query = mysqli_query($___mysqli_ston, "SELECT `members_pass_salt`, `members_pass_hash` FROM `members` WHERE `name` = '$s'");
$results = mysqli_fetch_assoc($query);
$password = md5(md5($results['members_pass_salt']).md5($password));
return $password == $results['members_pass_hash'];
}
Also take a look at PDO.

PHP MYSQL verify user from table and set SESSION 'username'

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 }

Php log in allows entry with no user/pass

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.";
}
?>

Categories