User authentication PHP mySQL not working - php

So I am currently building a user authentication system using php and mysql in Xampp.
I have managed to get it to recognize if a user exists by their email address, but the other functions don't seem to be working. For example to check if the user has activated their account or not comes back as they haven't even if I change their active status to 1 in the database. Or with the login function even if both email and password are correct it will say that they are incorrect.
Here is my login.php script
<?php
include 'init.php';
function sanitize($data){
return mysql_real_escape_string($data);
}
//check if user exists
function user_exists($email){
$email = sanitize($email);
//$query = mysql_query("SELECT COUNT('ID') FROM 'register' WHERE 'email' = '$email'");
return (mysql_result(mysql_query("SELECT COUNT(ID) FROM register WHERE email = '$email'"),0) == 1)? true : false;
}
//check if user has activated account
function user_activate($email){
$email = sanitize($email);
//$query = mysql_query("SELECT COUNT('ID') FROM 'register' WHERE 'email' = '$email'");
return (mysql_result(mysql_query("SELECT COUNT(ID) FROM register WHERE email = '$email' AND 'active' =1"),0) == 1)? true : false;
}
function user_id_from_email($email){
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT id FROM register WHERE email = '$email'"),0,'id'));
}
function login($email,$password){
$user_id = user_id_from_email($email);
$email = sanitize($email);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(id) FROM register WHERE email = '$email' AND 'password' ='$password'"),0) == 1)? $user_id : false;
}
if(empty($_POST)=== false){
$email = $_POST['email'];
$password = $_POST['password'];
}
if(empty($email)|| empty($password) === true){
$errors[] = "You must enter a username and a password";
}
else if(user_exists($email) === false){
$errors[] = "Email address is not registered";
}
else if(user_activate($email) === false){
$errors[] = "You haven't activated your account yet";
}
else{
$login = login($email, $password);
if($login === false){
$errors[] = "email/password are incorrect";
} else {
echo "ok";
}
}
print_r($errors);
/*$email = $_POST['email'];
$password = $_POST['password'];
if($email&&$password){
$connect = mysql_connect("localhost","root","") or die ("Couldn't Connect");
mysql_select_db("users") or die("Couldn't find Database");
}
else
die("Please enter a username and a password");
$query = mysql_query("SELECT * FROM register WHERE email = '$email'");
$numrows = mysql_num_rows($query);
echo $numrows;*/
?>
My database is called 'users' and at the moment only has 1 table called 'register'. With the rows: id, firstname, lastname, email, password, and active.

in your function login, try to remove the quotes ' arround the field name password. Or prefer use this one ` .
And take care, you are using function mysql_result and mysql_query that both are no longer supported in PHP 7.0
As you can see here :
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-result.php

Related

Can't login using password_verify

I'm trying to make a register/login system. The hashed passwords are saved into database successfully but when i try to login it says "Invalid login" which means it doesn't verify the password. Help me with this, it's my first time using password hash and verify
Signup.php
<?php
include('AdminPanel/connect.php');
$name = $_POST['txt_name'];
$email = $_POST['txt_email'];
$password = password_hash($_POST['txt_pass'], PASSWORD_DEFAULT);
$radioVal = $_POST['Gender'];
if($radioVal == "Male")
{
$radioVal = "Male";
}
else if ($radioVal == "Female")
{
$radioVal = "Female";
}
$queryget = mysqli_query($con,"SELECT Email FROM signup WHERE Email='$email'") or die ("Query didnt work");
$row = mysqli_fetch_array($queryget);
$emaildb = $row['Email'];
if($emaildb!=$email){
echo"success";
$insert = mysqli_query($con,"insert into signup (Name,Email,Password,Gender) values ('$name','$email','$password','$radioVal')");
}else{
echo"Email already exists";
}
?>
Login.php
<?php
include('AdminPanel/connect.php');
session_start();
$email = $_POST['txt_email'];
$password = $_POST['txt_pass'];
$info = mysqli_query($con,"select count(*) from signup where Email = '$email' and Password = '$password'");
$row = mysqli_fetch_array($info);
if (($row[0] > 0) && password_verify($password, $row['Password']))
{
$_SESSION['txt_email']=$email;
echo "success";
}
else
{
echo "Invalid login<br>Please re-enter your credentials";
}
?>
You're selecting count(*):
$info = mysqli_query(
$con, "select count(*) from signup where Email = '$email' and Password = '$password'"
);
But then referencing a field:
$row['Password']
You need to select (at least) the field, but leave out the condition on password because the password you get won't match what's in the database:
$info = mysqli_query(
$con, "select * from signup where Email = '$email'"
);
Also, don't do that, because SQL injection.

cannot log in with correct password and username. keep false

when I log in, even the password and username are correct, it keep error.
Array ( [0] => That user/password combination is incorrect )
the username and password is active and existed.
login.php
<?php
include 'init.php';
if(empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['pwd1'];
if(empty($username)|| empty($password)) {
echo 'You need to enter username and password';
}
else if(user_exists($username) === true){
if(user_active($username) === true){
$login = login($username, $password);
if($login === false){
$errors[] = 'That user/password combination is incorrect' ;
} else{
$_SESSION['user_id'] = $login;
ob_end_clean();
header('Location:forum.php');
exit();
}
}
else{$errors[] = 'You haven\'t activated your account!';}
}
else{$errors[] = 'We can\'t find that username. Have you registered?';}
print_r($errors);
}
?>
users.php
<?php
function logged_in(){
return (isset($_SESSION['user_id'])) ? true :false;
}
function user_exists($username){
$username = sanitize($username);
$sql = "SELECT COUNT(user_id) FROM `user` WHERE username = '$username'";
$result = mysql_query( $sql);
return (mysql_result($result,0) ==1) ? true : false;
}
function user_active($username){
$username = sanitize($username);
$sql ="SELECT COUNT(user_id) FROM `user` WHERE username = '$username' AND `active` = 1";
$result = mysql_query( $sql);
if ($result === false){
return false;
}
return (mysql_result($result,0) ==1) ? true : false;
}
function user_id_from_username($username){
$username = sanitize($username);
$sql = "SELECT user_id FROM `user` WHERE username = '$username'";
$result = mysql_query( $sql);
if ($result === false){
return false;
}
return mysql_result($result,0, 'user_id');
}
function login($username, $password){
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT COUNT(user_id)
FROM `user`
WHERE username ='$username' AND pwd1 ='$password'");
$row = mysql_fetch_row($query);
if($row[0]>0){
return user_id;
}else{
return false;
}
}
?>
general.php
<?php
function sanitize($data){
return mysql_real_escape_string($data);}
?>
init.php
<?php
ob_start();
session_start();
require 'connect.php';
require 'general.php';
require 'users.php';
$errors = array();
?>
You don't assign $login to $_SESSION['user_id'], because you call die($login); before that, which is same as exit, nothing is parsed after that. Change the order.
And pray that your sanitize function works. Anyway, you had better switch to PDO, because mysql_ functions are deprecated and not safe. Even if you sanitize your $_POST and $_GET, you can still have malicious values selected from your database or from XML you parse or from other source.

Cannot add to mySQL database using XAMPP for mac

I hello I am currently trying to add data to my user login database however for some reason my database it not being updated when I register a new user.
here is my code from user.inc.php:
<?php
//checks if username already exists in database
function user_exists($user)
{
$user = mysqli_real_escape_string($user);
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= ('$user')");
return (mysql_result($total, 0) == '1') ? true : false;
}
//checks if username and password combo is valid
function valid_credent($user, $pass)
{
$user = mysqli_real_escape_string($user);
$pass = sha1($pass);
$total = mysqli_query("SELECT COUNT user_id FROM users
WHERE user_name = '$user' AND
user_password = '$pass' ");
return(mysql_result($total, 0) == '1') ? true : false;
}
//add user to database
function add_user($user, $pass)
{
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$queryStr = "INSERT INTO users (user_name, user_password) VALUES ('$user', '$pass')";
$R = mysqli_query($mysqli,$queryStr);
}
?>
I also have warning on my register page when I try to add view errors
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/PostalCloud/core/user.inc.php on line 8
line 8:
return (mysql_result($total, 0) == '1') ? true : false;
I have tried using "sanitize()" however that doesn't exists.
UPDATE: Still getting errors after modifying code. Here part of my register.php code and I have a init.inc.php that uses mysqli to connect to database.
<?php
include('init.inc.php');
$errors = array();
if(isset($_POST['username'], $_POST['password'], $_POST['repeatPassword']))
{
if(empty($_POST['username']))
{
$errors[] = 'The username cannot by empty. ';
}
if(empty($_POST['password']) || empty($_POST['repeatPassword']))
{
$errors[] = 'The password cannot by empty. ';
}
if($_POST['password'] !== $_POST['repeatPassword'])
{
$errors[] = 'Password verification failed. ';
}
if(user_exists($_POST['username']))
{
$errors[] = 'The username you entered is already taken. ';
}
if(empty($errors))
{
add_user($_POST['username'], $_POST['password']);
$_SESSION['username'] = htmlentities($_POST['username']);
header('Location: protected.php');
die();
}
}
?>
init.inc.php:
<?php
session_start();
$exceptions = array('register', 'login');
$page = substr(end(explode('/',$_SERVER['SCRIPT_NAME'])), 0, -4);
if(in_array($page, $exceptions) === false)
{
if(isset($_SESSION['username']) === false)
{
header('Location: login.php');
die();
}
}
$mysqli = mysqli_connect('localhost','root','', 'user_system');
$path = dirname(__FILE__);
include("{$path}/core/user.inc.php");
?>
The problem is that mysql_query() is returning a boolean instead of a result resource. There are two reasons this can happen:
You performed query that returns success/fail instead of a result
set (e.g. UPDATE)
Your query failed
your query contains single quotes on column names..this should be removed :
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= '$user'");

login form email and password incorrect error

I created a login form but when i try to login, it says email or password is incorrect but I'm going in the right email and password.
I create user in my database users table but again again i get this error. All error is ok when i try to emtpy email and password it says You need to entere a email and password.
and activated error also ok.I am entering the correct password and email address. Gives me the error.
This is users.php
<?php
function user_exists($email) {
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false;
}
function user_active($email) {
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email' AND `active` = 1"), 0) == 1) ? true : false;
}
function user_id_from_email($email) {
$email = sanitize($email);
return mysql_result(mysql_query("SELECT `id` FROM `users` WHERE `email` = '$email'"), 0, 'id');
}
function login($email, $password) {
$id = user_id_from_email($email);
$email = sanitize($email);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT (`id`) FROM `users` WHERE `email` = '$email' AND `password` = '$password'"), 0 ) == 1) ? $id : false;
}
?>
And this is login.php
<?php
include("core/init.php");
if(empty($_POST) === false) {
$email = $_POST['email'];
$password = $_POST['password'];
if (empty($email) === true || empty($password) === true) {
$errors[] = 'You need to enter a email and password';
} else if (user_exists($email) === false) {
$errors[] = 'We can\'t find that email. Have you registered ?';
} else if (user_active($email) === false) {
$errors[] = 'You have\'t activated your account';
} else {
$login = login($email, $password);
if ($login === false) {
$errors[] = 'That email/passowrd cocmbination is incorrect';
}else {
$_SESSION['id'] = $login;
header('Location: main.php');
exit();
}
}
print_r ($errors);
}
?>
Sorry, but there's a whole load of stuff which is wrong - lots of it may be producing errors.
1) there is no 'sanitize' function in php and you haven't told us what it does.
2) your login.php does niclude users.php
3) generating an md5 hash of the password is far from secure (it should be a slated sha1 hash as a minimum)
4) you never check for errors being returned by the DBMS
5) ...actually - that's not true - you compare the return value from the functions in users.php to false - and you'll only get false if the query fails - not if it returns 0 rows
Consider....
function do_something_with_email($email, &$err) {
$email = mysql_real_escape_string($email);
if (!($res=mysql_query("SELECT `id` FROM `users` WHERE `email` = '$email'"))) {
$err=mysql_error();
return false;
}
if (!($data=mysql_fetch_array($res)) {
$err=mysql_error();
return false;
}
return $data[0];
}
switch (do_something_with_email($email, $err)) {
case false:
die ($err);
case 0:
print "No records matched";
break;
default:
print "OK";
break;
}

What is wrong with this PHP/MySQL code?

if(!empty($username) && !empty($email) && !empty($password) && !empty($confirm_password)){
$username = htmlentities($username);
$username = stripslashes($username);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$username = preg_replace("[^A-Za-z0-9]", "", $username);
$email = htmlentities($email);
$email = stripslashes($email);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$email = preg_replace("[^A-Za-z0-9]", "", $email);
if(strstr($email, "#") && strstr($email, ".")) {
require("$baseURL/scripts/connect.php");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$email'") or die(mysql_error());
$numrows_checkemail = mysql_num_rows($checkemail);
if($numrows_checkemail > 0) {
require("$baseURL/scripts/connect.php");
$checkusername = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
$numrows_checkusername = mysql_num_rows($checkusername);
if($numrows_checkusername > 0) {
if($password == $confirm_password) {
$hashpass = md5(md5($password));
//All set to insert into the db
require("$baseURL/scripts/connect.php");
mysql_query("INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$hashpass')") or die(mysql_error());
$this->noticeMsg = "You have been signed up successfully!";
} else {
$this->errorMsg = "Uh-oh, looks like your passwords do not match!";
}
} else {
$this->errorMsg = "Oops, looks like that username is already in use! Please pick a different username.";
}
} else {
$this->errorMsg = "That email is already in use, please sign up with another email.";
}
} else {
$this->errorMsg = "Please enter a valid email address!";
}
} else {
$this->errorMsg = "Please fill in all the fields!";
}
The error I keep getting is "That email is already in use, please sign up with another email." even though the right file is being "required" and is connected to the database properly. The problem is most likely at the $numrows_checkemail part because when I use if($numrows_checkemail == 0) it works just fine. Why won't the ">" symbol work?
Am I doing something wrong?
Thank you
if($numrows_checkemail > 0) will return true only if $numrows_checkemail is bigger than 0.
You need to check for $numrows_checkemail == 0 or empty($numrows_checkemail)
The > is reversing your logic;
$numrows_checkemail > 0 is true if at least one user with that email already exists in the database (ie if there is more than zero rows in the database with that email)
$numrows_checkemail == 0 is true if no user with that email already exists in the database (ie if there isn't any row in the database with that email)

Categories