Check for username availability php - php

<?php
$con = mysqli_connect('localhost','root','[mypassword]','dbhwsource');
if(isset($_GET['username'])){
$username = $con->real_escape_string($_GET['username']);
$test = $con->query("SELECT username FROM users WHERE username='$username'");
if($test!=false) die("usererror");
}
if(isset($_GET['email'])){
$email = $con->real_escape_string($_GET['email']);
$test = $con->query("select * from users where email='$email'");
if($test!=false) die("emailerror");
}
$con->close();
echo "ok";
?>
So I'm just trying to check to see if the username / email is available or not, but all i get is "usererror" no matter what the input username is! I'm just frustrated and have searched for sample code everywhere and the code looks like there's nothing wrong with it. What am I doing wrong?
EDIT:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
This worked!

Since your query returns true, this line if($test!=false) die("usererror"); gets executed,
should be something like
$test = $con->query("SELECT username FROM users WHERE username='$username'");
$row_cnt = $test->num_rows;
if( $row_cnt > 0 ) {
//you already have user with this name, do something
}

$con->query returns a result object if the query was successful. This doesn't say anything about how many rows where found or whether the query matched anything, it just means the query executed successfully. Therefore your $test!=false test always succeeds; only in the case of a database error would it fail.
Do the query as SELECT COUNT(*) FROM ..., then fetch the first row of the result and see if the count is > 0.

I recently did something like this for an android app. you should really check this site out. It helped me tremendously. This is a detailed example of having a PHP API for an aplication. Specifically logging in.
To be specific though, here is a snippet from the page for the PHP
/*
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}

This worked for me:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");

Your code is really not secure not optimized anybody can login with sql injection in your code.
and your code is right as you are checking thar (test != false) it means it is true that's why your code og usererror is executing
here is some tips and always use this style for security and optimization
do same for $email
third after running the query do not check if it is true or false but check again after query
if($test->username === $_GET['username']) { do something }
check sql injections on Google why i did this

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.

Problems updating MySQL, "username" in a table using PHP

I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.

My Login PHP script is malfunctioning

So I am having problems with my login script. I have a salted MD5 hash stored in my database, and well... When I use this statement followed by this code, it logs in whatever the password is.
I'm not sure if it's the syntax, or it's just the way I use it, but it logs in if the user exists even if the password is 'lalala' and the person types in 'chicken'.
$sql = ("select * from website where `Email`='$user' and `Password`='$pass'");
$query = mysql_query($sql);
if ($query) {
$data = mysql_fetch_array($query, MYSQL_ASSOC);
if (sizeof($data) > 0) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location: /');
die;
}
}
This is how it is run:
index.php --> Presses login (Sends POST data) --> login.php (This script) --> (If it logs in, it returns to /index.php, but if not, it will go to /login.php.
I have a test account on there called 'blah' with the salted MD5 hashed as 'lolcatz'. If I were to type in 'blah' in the username part, with the password as 'stackoverflow', it will go to 'index.php'
Any ideas?
try to print_r($data) to see what the mysql_fetch_array function returns. It could be that it returns FALSE, which will overpass your condition if (sizeof($data) > 0)
Your logic is incorrect. mysql_fetch_array() will return an array representing one SINGLE row of data from the query results, or a boolean FALSE in case of failure (query has no rows, or you're fetching from something OTHER than a query result).
You should be doing:
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
... user exists ...
} else {
... user does not exist ...
}
Don't use this:
if ($query) {
$data = mysql_fetch_array($query, MYSQL_ASSOC);
if (sizeof($data) > 0) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location: /');
die;
}
}
What is the reason behind measuring the size of data? That is a poor way to validate.
Do this instead :
if ($query) {
if(mysql_num_rows($query)>0){
// In the above line, we check a user with that username and password exists
$_SESSION['vuser'] == $_POST['vuser'];
header('Location: /');
} else echo "Bad password";
} else echo "Connection error";
As a side note, please stop using mysql_* functions now or real soon. They are going to be removed in the next version of PHP, and are less secure. You can use the PHP PDO Class.
I am also assuming you are not storing the $username and $pass directly in the database. If you are, stop it now, and use hash functions to store the password. You can use md5 and/or sha1 hash methods.
As it is said, you can also use mysqli similar down below
$dbq=("SELECT * FROM users where username='$uname'");
$dbresult=mysqli_query($con,$dbq);
where $con is the connection query which you've to write in mysqli.
Now you can fetch the data similar down below.
$obj=$dbresult->fetch_object();
$dbmail=$obj->Email;
$dbuname=$obj->Password;
$sql = ("select * from website where `Email`='$user' and `Password`='$pass'");
$query = mysql_query($sql);
$row = mysql_fetch_array($query, MYSQL_ASSOC);
if ($row) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location:"go where ever you want to i dont care"');
}
else{ //some error message}

SQL/PHP "WHERE" not returning correct value?

The code will display the returned values and and if it is greater than one it will return "Yes". But I am having trouble with the WHERE clause in $check. When I take it out the code works just fine but when I add it, the page returns incorrect values. Any ideas what's wrong?
<?php
$con = mysqli_connect("127.0.0.1","root","","lian");
$u= $_GET['username'];
$pw = $_GET['password'];
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
$login = mysqli_query($con,$check) or die(mysqli_error($con));
$num_rows = mysqli_num_rows($login);
echo "$num_rows \n";
if (mysqli_num_rows($login) == 1) {
$row = mysqli_fetch_assoc($login);
echo 'Yes';
exit;
}
else {
echo 'No';
exit;
}
Leaving aside the injection vulnerabilities, it may be because of special characters or whitespace. Try trim'ing your GET values.
$u = trim($_GET['username']);
$pwd = trim($_GET['password']);
Are you getting the number of results as 0? Also try echoing the statement in a development environment to check exactly what the statement is.
Try like this
$u= trim(mysqli_real_escape_string($_GET['username']));
$pw = trim(mysqli_real_escape_string($_GET['password']));
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
Also I hope you are ensuring unique combination of username and password.
Because suppose there are two entries in your users table
username="abc" password ="12345"
Then mysqli_num_rows() function will return two rows and the
if (mysqli_num_rows($login) == 1)
condition will return false meaning the user desn't exist.
The above comments are valid to improve the security of your code and protect vs sql injection.
Regarding your actual problem if the code executes correctly when you don't have the where clause in place but fails when you do there are a couple of possibilities:
The username or password are wrong - where wrong can mean they have extra whitespace, case insensitivities or that the column names are incorrect(case sensitive database?)
The string you are passing to the server is not displaying correctly.
Check both options by doing an echo of $u, $pw and $check right after you form your SQL string. If it's still not clear then copy whatever is echoed for $check and past it directly into the parser(management studio I guess?) and see what it returns.
Good Luck.

HOW do I check if password is updated in a table

I have written a script in php to reset user's password, and how do I check if password is updated in a table?
For example, if a data in the tuple/column has been changed, then send email. Please check comments in the script.
$dbcc = mysqli_connect(HOST,NAME,PASSWORD,DATABASE) or die('Error can not connect to database');
$query = "SELECT uid,email FROM `corporate` WHERE (email='$chk_email')";
$result = mysqli_query($dbc, $query);
//found
if(#mysqli_num_rows($result) == 1)
{
$ROW = mysqli_fetch_array($result);
$sent_email = $ROW['email']; //get email
$id = $ROW['uid']; //get uid
$new_password = generatePassword(8);//generates 8 char long random password
$enc_password = md5($new_password); //encrypt
$statement = "UPDATE corpoorate SET password=".$enc_password." WHERE uid ='$id'";
$go = mysqli_query($dbcc,$statement) or die(mysqli_error());
mysqli_close($dbcc);
/*
* HOW DO I CHECK IF PASSWORD IS UPDATED IN THE DATABASE?
* IF IT IS, SEND EMAIL
* IF $go==true does not work!
**/
if($go==true){
$sendmessage = "We have generated a new password token for you.\n Your password is reset to ".$new_password." \n Please note that this password is not secure. Once you login, please reset your password.\n ";
mail($sent_email,'Password Reset',$sendmessage,'From: address#gmail.com');
}
header("Location : http://limozoor.com/login/signin.php");
exit();
}//if
mysqli_close($dbcc);
Why don't you use mysqli_affected_rows?
// remove: $go = mysqli_query($dbcc,$statement) or die(mysqli_error());
$qry =# mysqli_query($dbcc, $statement);
$aff =# mysqli_affected_rows($dbcc);
if ($qry === true && $aff > 0) {
mail(...);
}
From manual;
mysqli_query:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
mysqli_affected_rows:
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
http://php.net/manual/en/mysqli.affected-rows.php
http://php.net/manual/en/mysqli.query.php
Because of your or die(mysqli_error());-condition the password will always be updated in the table if it reaches those lines of execution.
However, I am sceptic towards your if(#mysqli_num_rows($resultt) == 1) because if there is any error in your first SQL-query, you are supressing all error messages there (by using #), which makes me think that you never even try to execute the UPDATE statements.

Categories