Validate email with database - php

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
}

Related

the second condition of my login function is not working

i am trying to set a login function which match the username and the password existing in my database However the first condition is working perfectly but not the second one
<?php
if(isset($_POST['loginButton'])){
//taking user input
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
//Call of the login function through acccount variable
$result = $account->login($username, $password);
if($result == true){
header('location:index.php');
}
}
?>
<?php
class Account{
...
public function login($un , $pw){
$pw = md5($pw);
$query = mysqli_query($this->con , "SELECT * FROM users WHERE username = '$un' AND passwords = '$pw' ");
if(mysqli_num_rows($query) == 1){
return true;
}
else{
array_push($this->errorArray , Constants::$loginFailed);
return false;
}
}
}
?>
<?php
class Constants{
//Login constants
public static $loginFailed = "Your username or password was incorrect";
}
?>
i except it to return true so it will redirect me to the index page but actual input is false
Your Query will always return false, because it is not able to find the user with the given password, it is not the correct way to verify hashed password
//this is where the problem is, do not verify password like this:
$pw = md5($pw);
$query = mysqli_query($this->con , "SELECT * FROM users WHERE username
= '$un' AND passwords = '$pw' ");
This is the correct way of verifying hashed passwords (https://www.php.net/manual/en/function.password-verify.php):
if (password_verify($pw, $hash)) { //$hash password is from the DB
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
So In your sql Query get the user with the given username first
$query = mysqli_query($this->con , "SELECT * FROM users WHERE username = '$un'");
then Match the password from the DB with the current user given password $pw with password_verify function. so it will be something like this:
if($query){
$data = mysqli_fetch_row($query);
if (password_verify($pw, $data['passwords'])) { //$data['password'] password is from the DB
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
}

password_verify() does not match with password in database

I am creating a user login page. I used password($pass,PASSWORD_BCRYPT) in inserting the data into the database but on trying to verify the password with password_verify($password,$salt) the values does not match.
I am sure that the data $salt retrieved from the database is correct but it does not match. Can you advise how I can troubleshoot it further? I have searched this thoroughly but cant find any answer.
This is my login code below:
<?php
// if form submitted
// check supplied login credentials
// against database
}
else { $username = $_POST['username'];
$password = $_POST['password'];
// check input
if (empty($username)) {
die('ERROR: Please enter your username');
}
if (empty($password)) {
die('ERROR: Please enter your password');
}
// attempt database connection
include("memberconnect.php");
$pdo = new mysqli($host,$user,$password,$database);
if (!$pdo) {
die("ERROR: Could not connect: (" . $pdo->errno .")" .$pdo->error);
}
// escape special characters in input
$username = stripslashes($username);
// check if usernames exists
$sql = "SELECT Login_Name FROM memberdirectory WHERE Login_Name = '$username ' ";
if ($result = mysqli_query($pdo,$sql)) {
$row = mysqli_num_rows($result);
// if yes, fetch the encrypted password
if ($row == 1) {
$sql = "SELECT Password FROM memberdirectory WHERE Login_Name = '$username' ";
// encrypt the password entered into the form
// test it against the encrypted password stored in the database
// if the two match, the password is correct
if ($result = mysqli_query($pdo,$sql)) {
$row = mysqli_fetch_array($result);
$salt = $row[0];
if (password_verify($password,$salt))
{
// password correct
// start a new session
// save the username to the session
// if required, set a cookie with the username
// redirect the browser to the main application page
session_start();
$_SESSION['username'] = $username;
if ($_POST['sticky']) {
setcookie('name', $_POST['username'], mktime()+86400);
}
header('Location: main.php');
}
else
{ echo 'You entered an incorrect password.';
echo strlen($salt);
var_dump(password_verify('$password',$salt));
var_dump($salt);
}
}
else {
die("ERROR: Could not execute $sql (" .$pdo->errno.")".$pdo->error);
}
} else {
echo 'You entered an incorrect username.';
}
} else {
die( "ERROR: Could not execute $sql (" .$pdo->errno.")".$pdo->error);
}
// close connection
unset($pdo); }
?>
password_verify checks the password against a hash. To get the hash, which by the looks would be saved to the database, you would use password_hash. This is even stated in password_verify php.net manual pages. Please recheck your hashing.
The only password function I am aware of is for MySQL that is used mainly for MySQL authentication. If you are using a custom function password, you will have to resend the entered password and salt through or reverse engineer the hash.

how to allow email as well as username to login into account?

for a long time i have been using username as only option to log in to my website account but most of the users forget their username so i want to add email and username both as options to login.
here is my code to create a session and log in the user.
<?php
if(isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9#._\(\)\']#i', '', $_POST["user_login"]);
$password_login = preg_replace('#[^A-Za-z0-9!#._]#i', '', $_POST["password_login"]);
$md5password_login = md5($password_login);
$sql = mysql_query("SELECT id FROM users WHERE username='$user_login' AND password='$md5password_login' LIMIT 1");
//check for their existance
$userCount = mysql_num_rows($sql); //count the number of rows returned
if ($userCount == 1) {
while($row = mysql_fetch_array($sql)) {
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
exit("<meta http-equiv=\"refresh\" content=\"0\">");
} else {
echo "Your Username or Password is Incorrect. please try again.";
exit();
}
}
?>
How can i add email with username login ?
Note : the teacher who taught me php showed me how to use mysql_query and not the latest version and i know it is being deprecated so i have already changed all my query's, this is an old code.
You can give option on your login form to select login (radio button) type as username or Email.Then change your query accordingly:
if($logintype=="Username")
{
//Current Username query
}
else
{
//Email Login query
}
or you can use both in query as:
$sql = mysql_query("SELECT id FROM users WHERE (username='$user_login' || email='$_POST[user_login]') AND password='$md5password_login' LIMIT 1");
try this.. by checking post data is email or not
$email = $_POST["user_name"];
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
// email query
}
else
{
// username query
}

php username check on database when user already taken

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'];
}

php user login anf function

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.

Categories