Hi i have a registration system, and it works well and save to database, I have a problem in checking on the database for the username if already exists. My script on checking database is wrong. Can someone help me on this? Below is my code
<?php
if(empty($_POST['username'])){
$username_error = "Please Input Username";
}else{
if( 6 > mb_strlen($_POST['username']) || 20 < mb_strlen($_POST['username'])){
$username_error = "username must be at least 6 characters.";
}else{
$sql = "SELECT
members.username
FROM
members
WHERE username = $username";
$res = mysql_query($sql);
if(mysql_num_rows($res)){
$username_exists = "Username is already taken.";
}else{
$username = $_POST['username'];
}
}
}
?>
problem is only in the else statement
Change :
$sql = "SELECT
members.username
FROM
members
WHERE username = $username";
To:
$sql = "SELECT
members.username
FROM
members
WHERE username = '".mysql_real_escape_string($username)."'";
$users =mysql_query($sql);
if(mysql_num_rows($users )){
$username_exists = "Username is already taken.";
}{
$username = $_POST['username'];
}
Have in mind, you need to escape your user name to avoid SQL injection! And avoid using mysql_ functions!
Before you read on; this is prone to SQL injection, and I'd love to point you to PDO.
Change your SQL statement to treat $username as a string;
SELECT members.username
FROM members
WHERE username = '$username'
Then remove the following line,
mysql_query($sql);
And finally change your if() { } condition to;
if(mysql_num_rows(mysql_query($sql))>0){
I have tried to help you with this code. Pay attention to comments. I have done more then just, answer your question: there are a bit changed logic, added sanitize of $username...
<?php
// at first let's define this variables (just for any case)
$username_error = null;
$username_exists = null;
// get username
$username = $_POST['username'];
// let's check it
if (empty($username)) {
$username_error = "Please Input Username";
// don't know in what context you use this code
// so here you need to return from function or exit
return;
}
// ... and sanitize
$username = filter_var($username, FILTER_SANITIZE_SPECIAL_CHARS); // just for example
// actually, I use active record, so can't suggest 100%-security way
// check lenght
if (mb_strlen($username) < 6 || mb_strlen($username) > 20) {
$username_error = "username must be at least 6 characters.";
// also let's exit or return
return;
}
// and now let's check it in DB
$sql = "SELECT
members.username
FROM
members
WHERE username = '$username'";
// !!! pay attention!!!
$result = mysql_query($sql); // we need append this mysql result to some variable
if (mysql_num_rows($result) > 0) { // and here we check num_rows of that result, not just tring with query!
$username_exists = "Username is already taken.";
// also let's exit or return
return;
}
// if we are in here we have sanitized $username, that's not in use.
// Enjoy!
var qc=document.forms["regform"]["email"].value;
if(qc!='') {
alert('in');
$.ajax({
url: 'search.php',
data: "check_qc=" + qc,
async:false,
success: function(response) {
if(response==1)
{
alert('Already Exists');
return false;
}
}
});
}
Now, in search.php file
$qc = $_GET['check_qc'];
$sel="select * from register where email='".$qc."'";
$res= mysql_query($sel);
$co= mysql_num_rows($res);
// echo $co;
if(count($co)>0)
echo "1";
else
echo "0";
if(mysql_num_rows($sql)>0){
$username_exists = "Username is already taken.";
}else{
$username = $_POST['username'];
}
Although you should be using PDO or something else for sanitization.
Correction:
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)){
$username_exists = "Username is already taken.";
}else{
$username = $_POST['username'];
}
Related
The following code should be straight forward and simple, the insert into the db on signup creates a hash, but later when I try to login with the same password the hash it is creating isn't matching up to what is in the database (I had print_r's throughout to verify). Can someone see if I'm just overlooking something dumb?
session_start();
require_once("login.php");
$error = "";
$email = "";
$password = "";
if (isset($_GET['logout'])) {
unset($_SESSION['id']);
setcookie('id', '', time() - 60*60);
$_COOKIE['id'] = "";
} else {
if (isset($_SESSION['id']) or isset($_COOKIE['id'])) {
header("Location: loggedinpage.php");
}
}
if (isset($_POST["submit"])) {
$link = mysqli_connect($hn, $un,$pw,$db);
if($link->connect_error) die("Fatal Errror.");
if (!$_POST["email"]) {
$error .="An email address is required<br>";
}
if (!$_POST["password"]) {
$error .="A password address is required<br>";
}
if ($error != "") {
$error= "<p>There were error(s) in your form:</p>".$error;
} else {
if ($_POST['signup'] == 1) {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link,$_POST['password']);
$query = "SELECT id FROM `users` WHERE email = '".$email."' LIMIT 1";
$result=$link->query($query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is taken.";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO `users`(`email`,`password`) VALUES ('".$email."', '".$hashedPassword."')";
if (!mysqli_query($link,$query)) {
$error = "<p>Could not sign you up, please try again later</p>";
} else {
$_SESSION['id'] = mysqli_insert_id($link);
if(isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', mysqli_insert_id($link), time()+60*60*24);
}
header("Location: loggedinpage.php");
}
}
} else {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
$query = "SELECT * FROM users WHERE email = '".$email."' LIMIT 1";
$result = $link->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if ($email == $row['email'] and password_verify($password,$row['password'])) {
if (isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', $row['id'], time()+60*60*24);
header("Location: loggedinpage.php");
}
} else {
$error = "Incorrect Username/Password combination";
}
}
}
}
}
Although it's tucked away at the end of a paragraph, PHP documentation does say that "it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice)."
The current default algorithm, bcrypt, generates hashes that are 60 characters long. If your database column cannot hold at least this many characters, your hashes will be truncated and verification will fail.
You've got a few other problems as well:
You're modifying the password before generating the hash (with mysqli_real_escape_string())
You're not using prepared statements
You appear to be relying on cookies for authentication. Cookies are user-generated data, they are not to be trusted! This is why PHP provides session support, because the data is stored on the server.
You should not be checking for an existing email address using a query, instead you should have a unique index set on the email column in the database.
try
if(password_verify($password, (string)$row->password)){
//Your Code
}
because of password_verify function return Boolean only true or false
And
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
Only add once when you Insert to Sql (new user)
I am doing a password reset page for my website and when a user puts a new password on the <form method="post" action="passVerif.php"> it goes to the PHP with this code:
Until now I cannot make the php compare the two new entered passwords to verify if they are equal or not, it simply jumps over that part.
P.S. don't mind the $senha = md5($password) it is like this for easy troubleshoot on localhost (MAMP).
<?php
session_start();
include("connectivity.php");
$user_id = $_SESSION['ResetUtilizadorID'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$sql = mysqli_query($conn, "SELECT FROM usuarios WHERE id =".$user_id."");
$password = $password1;
$senha = md5($password);
$adminID = $_SESSION['usuarioNiveisAcessoId'];
if (strcmp($user_id,$adminID) == 0) {
$_SESSION['avisoReset'] = "not possible to change admin password.";
header('Location: ../login/reset_password.php');
} else {
while ($row = mysqli_fetch_array($query)) {
if ($senha == $row['senha']){
$_SESSION['avisoReset'] = "password taken";
header('Location: ../login/reset_password.php');
}
}
if ($password1 == $password2){
mysqli_query($conn, "UPDATE usuarios SET senha = '".$senha."' WHERE id='".$user_id."'");
$sql = 'SELECT * FROM usuarios';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
$_SESSION['avisoReset'] = "new passoword set";
//header('Location: ../login/reset_password.php');
} else {
$_SESSION['avisoReset'] = "Passwords not equal!";
header('Location: ../login/reset_password.php');
}
}
?>
Why are you using strpos? strpos finds the position of the first occurrence of a substring in a string. So the password could be a subset of another string (the stored password) and still evaluate to true for your use case.
if (strpos($user_id,$adminID) == true)
You should instead use strcmp (Binary safe string comparison):
if (strcmp($user_id,$adminID) == 0)
I solved the problem by adding a username and then comparing the user input data to the DB. So the problem of multiple users by any chance use the same password it is all good.
After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;
if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if(empty($username) || empty($password)) {
$error = 1;
$error_message = 'Please fill in all the required fields.';
} else {
get_login_name($username, $password);
//The commented line works...
//$query = mysql_query("SELECT /* user_logged true, page login */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1");
}
if(mysql_num_rows(get_login_name($username, $password)) == 0) {
echo get_login_name($username, $password);
$error = 1;
$error_message = 'Incorrect username or password.';
} elseif ($error == 0) {
//Other stuff....
}
}
Function:
function get_login_name($password, $username) {
global $myDB;
global $config;
$query = "SELECT /* page == login, functions.php */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1";
$result = $myDB->Execute($query) or die(GetDbError($myDB->ErrorMsg()));
return $result;
}
How properly check if username or password incorrect ? (part if(mysql_num_rows(g.....)
In my opinion something wrong i have done ir function get_login_name with return and checking. By the way, using adodb.
EDIT:
After all i decided a bit test it, so, let's leave function as it now and let's check username and password part:
if (!is_null(get_login_name($password, $username))) {
echo get_login_name($password, $username);
$error = 1;
$error_message = 'Incorrect username or password.';
}
If username or password incorrect ir gives me:
username,password which mean result doesn't found at all (no user, if user correct gives same)
Ok, let's enter valid user and pass, and it gaves:
username,password zero,0a706ce75f3bc195c8ed7be5a21d3766abb0d384
What's wrong ?
Essentially, if get_login_name has a return, that means the query returned a match for username and password which means the combination is correct, otherwise, no result means there's no match so you could say either username or password is incorrect (because they don't exist or one of them is wrong). If $Result has a value using get_login_name would likely to be just:
if (!is_null(get_login_name($password, $username)))
// correct
else
// incorrect
Play around with it and see the results.
Ech, after testing managed it to work :)
That seems this part fails :/
if (!is_null(get_login_name($password, $username)))
So, hole code:
if (!$myDB->Affected_Rows()) {
//if(mysql_num_rows($query) == 0) {
$error = 1;
$error_message = 'Incorrect username or password.';
}
What i have ? Just changed it to:
if (!$myDB->Affected_Rows()) {
Thank you all guys who tryed help.
I have created a form and have validated everything using PHP, but can't figure out how to validate email from database. If I have the entered username in the database, I want it to display an error. I have connect.php and
just for an example -
here's how i validate password -
if(!empty($_POST['password']))
{
if($_POST['password'] != $_POST['cpass'])
{
$errors[] = 'The password and confirm password do not match.';
}
else
{
$p=trim($_POST['password']);
}
}
here is what i'm trying to do -
$getusername = "SELECT username FROM users WHERE ($u,$username)";
if($getusername)
{
echo 'Username is already in use.';
}
else
{
$g=trim($_POST['username']);
}
THIS RESULTS IN A PARSE ERROR.
// first define the username from the $_POST variable
// make sure to escape the value to prevent SQL injection
$username = mysql_real_escape_string(trim($_POST['username']));
// select a user with the posted username
$sql = "SELECT username FROM users WHERE username = '$username' LIMIT 1";
// run the query
$res = mysql_query($sql) or die(mysql_error());
// see if there's a result
if (mysql_num_rows($res) > 0) {
echo 'This username is already taken';
} else {
// .. do stuff
}