Check for duplicate user account and email address - php

I am trying to check to see if a username or email address already existed in my database. I can currently connect to my database and retrieve data from my registering form. However, my SQL statements are not able to check my database to see if the user exists or not. Any help is appreciated, thanks.
<?php
require 'database.php';
$conn = Connect();
if ($conn == true){
echo "Successfully connected to database. <br><br>";}
$username = $_POST['screenname'];
$password = $_POST['password'];
$email = $_POST['email'];
echo "$username<br>"; //just checkin if it can grab data
echo "$password<br>";
echo "$email<br>";
$sql=mysql_query("SELECT * FROM users WHERE screenname = '$username'");
if(mysql_num_rows($sql)>=1)
{
echo "Username already exists";
}
else
{
//insert query goes here
}
$sql2=mysql_query("SELECT * FROM users WHERE email = '$email'");
if(mysql_num_rows($sql2)>=1)
{
echo "Email already exists";
}
else
{
//insert query
}
?>

Logic, programming and security (SQL injection attack) bugs fixed:
<?php
require 'database.php';
$conn = Connect();
if ($conn == true){
echo "Successfully connected to database. <br><br>";
}
$username = $_POST['screenname'];
$password = $_POST['password'];
$email = $_POST['email'];
echo "$username<br>"; //just checkin if it can grab data
echo "$password<br>";
echo "$email<br>";
$sql= sprintf("SELECT * FROM users WHERE screenname='%s' OR email='%s'",
mysql_real_escape_string($username),
mysql_real_escape_string($email)
);
if(mysql_num_rows($sql)>=1)
{
echo "Username or e-mail already exists";
}
else
{
//insert query goes here
}

Related

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

PHP password_verify always returns false

I´ve been working on an Android app which registers and logins users to a remote MySQL database. I have double-double checked my Android code and the information sent from the app to PHP.
Apparently, the problem is somewhere in the login.php file. Users are registered successfully, but I am unable to login after that.
My DB has 3 fields:
id / int(11)
email / varchar(255)
password /char(60)
Registering a user is giving me 60 characters hashes for the password field. So far, so good. But then when I try to login, I always get a failure response.
I'm using https://github.com/ircmaxell/password_compat since I'm limited to PHP 5.4
Here is my login PHP code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$email = $_POST['email'];
$passwordFromPost = $_POST['password'];
require_once('dbconnect.php');
$sql = "SELECT password FROM users WHERE email = '$email'";
$hash = mysqli_query($con, $sql);
require_once('lib/password.php');
if (password_verify($passwordFromPost, $hash)) {
echo 'success';
} else {
echo 'failure';
}
}
?>
And just in case, here is my registration PHP code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$email = $_POST['email'];
$passwordFromPost = $_POST['password'];
require_once('lib/password.php');
$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT);
if($hash) {
require_once('dbconnect.php');
$sql = "INSERT INTO users (email, password) VALUES ('$email','$hash')";
if(mysqli_query($con, $sql)){
echo "Registered succesfully";
} else {
echo "Unable to register the account";
}
} else {
echo 'error';
}
} else {
echo 'error';
}
?>
Any help will be much appreciated. Thank you.
You forgot to fetch your row. As such you were not verifying against a string.
<?php
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
password_verify($passwordFromPost, $row['password']);
You need to fetch the row:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$email = $_POST['email'];
$passwordFromPost = $_POST['password'];
require_once('dbconnect.php');
$sql = "SELECT password FROM users WHERE email = '$email'";
$hash = mysqli_query($con, $sql);
while ($row = mysqli_fetch_row($hash)) {
require_once('lib/password.php');
if (password_verify($passwordFromPost, $row["password"])) {
echo 'success';
} else {
echo 'failure';
}
}
}
?>
Reference: http://php.net/manual/en/mysqli-result.fetch-row.php
Your login php file should be
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$email = $_POST['email'];
$passwordFromPost = $_POST['password'];
require_once('dbconnect.php');
$sql = "SELECT password FROM users WHERE email = '$email'";
$rst = mysqli_query($con, $sql);
$hash = mysqli_fetch_row($rst);
require_once('lib/password.php');
if (password_verify($passwordFromPost, $hash['password'])) {
echo 'success';
} else {
echo 'failure';
}
}
?>

Secure more my register form

I want to make the following form more secure using bcrypt or something like that.
I am newbie to PHP, so take it slow and do not expect me to understund "don't use ..., use ...." without explanation.
Futhermore, i searched to Google for some forms tutorials but nothing found with encryption like bcrypt, hash256/512 etc.
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
require_once 'database.php';
$Username = $_POST['username']; #Username
$Password = $_POST['password']; #Password
$Password2 = $_POST['password2'];#Password
if(empty(Password2)){
echo "Please enter a valid confirmation password.";
$msg .=" Please enter a valid confirmation password.";
echo
"<script>
alert('$msg');
window.location.href='../register.html';
</script>";
exit;
}
if($Password !== Password2){
echo "Sorry, passwords do not match!";
$msgPass = "Sorry, passwords do not match!";
echo
"<script>
alert('$msgPass');
window.location.href='../register.html';
</script>";
exit;
}
function NewUser()
{
global $Username,$Password;
#Egxwrish stoixeiwn
$query = "INSERT INTO users (username,password) VALUES ('$Username','$Password')";
$data = mysql_query ($query) or die(mysql_error());
if($data)
{
return "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp()
{
global $Username,$Password;
if(!empty($Username)) //checking the 'username' name which is from register.html, if is it empty or have some text
{
$query = mysql_query("SELECT * FROM users WHERE username = '$Username'");
if(!$row = mysql_fetch_array($query))
{
$msg = NewUser();
echo $msg;
}
else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...!";
die(mysql_error());
}
}
}
if(isset($_POST['submit']))
{
//User registration
SignUp();
echo "Your account has been created successfully. \\n Thank you for joined us!";
$msgSuccess = "Your account has been created successfully. \\n Thank you for joined us!";
echo
"<script>
alert('$msgSuccess');
window.location.href='../index.php';
</script>";
}
?>
You are still using the deprecated MySQL. Consider using MySQLi or PDO instead. If you need it super secure, consider below instead. If you find it tough (its not but still if you face difficulties in understanding this), then first read some basics about PDO or MySQLi. Consider PHP 5.5 or later too.
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
<?php
// require_once 'database.php'; Consider PDO in your database.php like below
$pdo = new PDO('mysql:dbhost=dbhost;dbname=dbname', 'dbuser', 'dbpass'); // Provide your own credentials
$Username = $_POST['username']; #Username
$Password = $_POST['password']; #Password
$Password2 = $_POST['password2'];#Password
if(empty(Password2)){
echo "Please enter a valid confirmation password.";
$msg .=" Please enter a valid confirmation password.";
echo
"<script>
alert('$msg');
window.location.href='../register.html';
</script>";
exit;
}
if($Password !== $Password2){
echo "Sorry, passwords do not match!";
$msgPass = "Sorry, passwords do not match!";
echo
"<script>
alert('$msgPass');
window.location.href='../register.html';
</script>";
exit;
}
function NewUser()
{
global $Username,$Password;
#Egxwrish stoixeiwn
$hashed_pass = PASSWORD_HASH($Password, PASSWORD_DEFAULT);
$query = "INSERT INTO users (username,password) VALUES (:username, :password)";
$data = $pdo->prepare($query);
$data->execute(array(':username'=>$Username, ':password'=>$hashed_pass));
if($data->rowCount() > 0)
{
return "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp()
{
global $Username,$Password;
if(!empty($Username)) //checking the 'username' name which is from register.html, if is it empty or have some text
{
$query = ("SELECT * FROM users WHERE username = :username");
$query = $pdo->prepare($query);
$query->execute(array(':username'=>$Username));
if($query->rowCount() == 0)
{
$msg = NewUser();
echo $msg;
}
else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...!";
die();
}
}
}
if(isset($_POST['submit']))
{
//User registration
SignUp();
echo "Your account has been created successfully. \\n Thank you for joined us!";
$msgSuccess = "Your account has been created successfully. \\n Thank you for joined us!";
echo
"<script>
alert('$msgSuccess');
window.location.href='../index.php';
</script>";
}
?>
You are letting users know that someone else is already registered. This is called user enumeration. Depending on your business, this could be a vulnerability.
It's better to ask for email address only. If email exists in your db, send them an email, saying "hey, someone is trying to register with your email". If the user does not exist, send them an email with a link to step 2 to continue registration.

PHP login code error with mysql_query()

I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>

null values submitted to mysql database

I am trying to make a user system for my website but having some trouble with submitting it. It always submit a 0 to the database for everything. I have read on w3schools about global and local variables and I think this may be my problem but I don't know for sure.
Heres my code
<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];
if(!isset($firstname) || !isset($lastname) || !isset($username) || !isset($password) || !isset($passwordconf) || !isset($email) || !isset($securityq) || !isset($qanswer))
{
echo "You did not fill out the required fields.";
}
$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0)
{
echo "The username you entered is already taken";
}
$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
{
echo "The email you entered is already registered";
}
if($password != $passwordconf)
{
echo "The passwords you entered do not match";
}
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}
else
{
$salt = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
$hpassword = crypt($password,$salt);
$insert = "INSERT INTO users (firstname, lastname, username, password, email, securityq, qanswer, salt)
VALUES ('$firstname','$lastname','$username','$hpassword','$email','$securityq','$qanswer','$salt')";
mysql_query($insert);
if(!mysql_query($insert))
{
die('Could not submit');
}
else
{
echo "Information was submited. Please check your email for confirmation";
}
}
?>
Let me try to answer.
First of all, I agree with advice to move to PDO. mysql_* functions are deprecated. But if you wish to use it, escape every variable directly before sql due to '-symbols in your sql:
$hpassword = mysql_real_escape_string($hpassword );
As for me, the following syntax is easier to view rather than insert ... values():
$insert = "INSERT INTO `users`
SET `firstname` = '$firstname',
SET `hpassword` = '$hpassword'..."
Actually, I am trying to forgot this kind of code. I use PDO or comfortable uniDB class for simple apps.
Is it correct behaviour that it inserts user no matter errors like matching password? You should fix conditions.
Your conditions logic is wrong. You submit after if(!preg_match($regex, $email)). So if email is correct, it submits. Fix it as follows using ELSEIF
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(mysql_num_rows($emailquery) > 0){
echo "The email you entered is already registered";
}elseif($password != $passwordconf){
echo "The passwords you entered do not match";
}elseif(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}else{
// insertion code HERE
}

Categories