I created a registration and a login script which hash the password with salt exactly the same way, however when the user attempts to login using their password, the hashed login password and the one stored in the database differ, it was working a couple of days ago and I haven't changed anything in the login and registration scripts.
Here is what the stored credentials are
DBEMAIL: jd#gmail.com
DBPASSWORD:
addb18f27b6970082727069aa5853116223c5ab46f46a7b07340757804670aef61311ff0254ec45ea78d9ea6d8afb2cefdf3afd6bd4947f6fc558f46703fac1c
Here is what the User inserted credentials are:
UEMAIL: jd#gmail.com
UPASSWORD: 4123363f30664825356a238fe7a568910315e6f6aa8a57d0264844c641e856ab207200f4c75a532b2ebecdbd062bff31da101d973ab0f83eaefd2323a39a4a88
They are hashed using:
$salt = "salinger";
$hashed = hash_hmac("sha512", $password, $salt);
The full registration function (it's messy I know but it works (until now):
function registerUser($firstname, $surname, $email, $password, $secretQ, $secretA, $address, $city, $postcode) {
$flag = array();
$validEmail = validateEmail($email);
if (($validEmail) == true) {
//Do not flag
} else {
array_push($flag, 1);
}
if ((textOnly("First name", $firstname) == true) || ((textOnly("Surname", $surname)) == true) || ((textOnly("City", $city)) == true)) {
array_push($flag, 1);
}
if ((emptyField($firstname)) || (emptyField($surname)) || (emptyField($email)) || (emptyField($password)) || (emptyField($secretA)) || (emptyField($address)) || (emptyField($city)) || (emptyField($postcode))) {
array_push($flag, 1);
}
if (validPostcode($postcode) == false) {
array_push($flag, 1);
}
if (duplicateEmail($email) == true) {
array_push($flag, 1);
}
if (validatePassword($password) == false) {
array_push($flag, 1);
} else {
$password = validatePassword($password);
}
switch ($secretQ) {
case 1:
$secretQ = "Your mothers maiden name?";
break;
case 2:
$secretQ = "Name of your first pet?";
break;
case 3:
$secretQ = "The name of your high school?";
break;
case 4:
$secretQ = "Your favourite instrument?";
break;
}
$salt = "salinger";
$hashed = hash_hmac("sha512", $password, $salt);
if (!empty($flag)) {
echo "There are errors with your registration, go back and ammend it. <br /> << Back";
} else {
if ((isset($firstname)) && (isset($surname)) && (isset($email)) && (isset($password)) && (isset($secretQ)) && (isset($secretA)) && (isset($address)) && (isset($city)) && (isset($postcode))) {
$sql = "INSERT INTO customer (forename, surname, email, password, secretQ, secretA, address_street, address_city, address_postcode, member_type) VALUES ('$firstname', '$surname', '$email', '$hashed', '$secretQ', '$secretA', '$address', '$city', '$postcode', 'User');";
header("Location: index.php");
} else {
array_push($flag, 1);
}
}
$result = mysql_query($sql);
if (!$result) {
die(mysql_error());
}
}
The login function:
function loginUser($email, $password) {
if (validateEmail($email) == true) {
$sql = "SELECT customerid, forename, email, password, secretA, member_type FROM customer WHERE email = '$email'";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)) {
$DBid = $record['customerid'];
$DBemail = $record['email'];
$DBpassword = $record['password'];
$DBforename = $record['forename'];
$DBsecretA = $record['secretA'];
$DBmember = $record['member_type'];
}
if (!$result) {
die(mysql_error());
}
$salt = "salinger";
$hashed = hash_hmac("sha512", $password, $salt);
echo "DBEMAIL: $DBemail DBPASSWORD: $DBpassword <br/>";
echo "UEMAIL: $email UPASSWORD: $hashed <br/>";
if (($email == $DBemail) && ($hashed == $DBpassword)) {
$match = true;
} else {
$match = false;
}
if ($match == true) {
session_start();
$_SESSION['userid'] = $DBid;
$_SESSION['Active'] = true;
$_SESSION['forename'] = $DBforename;
$_SESSION['type'] = $DBmember;
header("Location: member.php");
} else {
echo "Incorrect credentials.";
}
} else {
echo "Invalid email address!";
}
return true;
}
In registerUser, I'd take a closer look at this:
...
if (validatePassword($password) == false) {
array_push($flag, 1);
} else {
$password = validatePassword($password);
}
...
$password will be overwritten, it appears, if it is a valid password. If all the passwords are the same in the database, then it's likely that $password is being set to true, and that's the value that's salted. Depending on how you use validatePassword, you may be able to remove the else-clause, leaving this:
...
if (validatePassword($password) == false) {
array_push($flag, 1);
}
...
Related
i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>
I am working on php and mysql code on making access to different pages based on the role of the user, through one Login Page.
Its working good for 'admin' page ..
but not able to login with 'normal type'
Little Help is really appreciated, Thank You
Here is my Code
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query) ;
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result) ;
if ($count == 1) {
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
}
elseif($row['user_type'] = 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
}
?>
Move your session code after if condition and then redirect. Also is there any specific reason to store password in session. == missing
Use proper filters for inputs.
if ($count == 1) {
if(!empty($row['user_type'])) {
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
//$_SESSION['password'] = $row['user_pass'];
}
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
}
elseif($row['user_type'] == 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
The logic test for the normal user was using a single = sign which sets a value rather than tests for equality - it needs to be ==
Also, I think the WRONG USERNAME OR PASSWORD wa at the wrong level - it needs to be the else to the record count
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result);
if ($count == 1) {
if($row['user_type'] == 'admin') {
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
/* require `==` here */
} elseif( $row['user_type'] == 'normal' ) {
header('Location: index.php');
} else {
die('unknown/unhandled user level');
}
/* changed location of this by one level */
} else {
echo "WRONG USERNAME OR PASSWORD";
}
}
?>
This is function for login.
It presumes password come from user with sha512 encryption (see js libs like https://github.com/emn178/js-sha512) - it's good for non-encrypted connections.
It uses salt, and have some protection from brute force, CSRF, XSS and SQL-injection.
static public function db_login($email, $p)
{
if ($stmt = Site::$db->prepare(
"SELECT id, password, salt, name
FROM user
JOIN contact ON contact_id = id
WHERE email = ?
LIMIT 1")
) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $db_password, $salt, $name);
$stmt->fetch();
// hash the password with the unique salt
$p = hash('sha512', $p . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (self::checkBrute($user_id) == true) {
// Account is locked
$res['code'] = 0;
$res['reason'] = 'trylimit';
$res['message'] = 'You try too many times. Come back on 30 minutes';
return $res;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $p) {
// Password is correct!
// Get the user-agent string of the user.
// CSRF
$user_browser = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_SPECIAL_CHARS);
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
Login::sec_session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = htmlspecialchars($email);
$_SESSION['name'] = htmlspecialchars($name);
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['login_string'] = hash('sha512', $p . $user_browser);
session_write_close();
// Login successful
$res['isLogined'] = 1;
$res['code'] = 1;
$res['name'] = $name;
$res['id'] = $user_id;
return $res;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
Site::$db->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
$res['code'] = 0;
$res['reason'] = 'pass';
$res['message'] = 'Wrong password';
return $res;
}
}
} else {
// No user exists.
$res['code'] = 0;
$res['reason'] = 'user';
$res['message'] = 'We have no such email';
return $res;
}
}
$res['code'] = 0;
$res['reason'] = 'SQL-error';
return $res;
}
So I'm trying to make a fairly simple login system, but for some reason the hashed password that is being sent to my database is not hashing correctly. I checked my database and the stored password is not what the sha256 hashed with the generated salt appended is not what it's supposed to be. Here's my code for generating the hash that's being uploaded to the database:
<?php
include "connection.php";
//Check Connection
if ($connect->connect_error) {
echo "Failed to connect to server: " . mysqli_connect_error();
}
//Reset all Checks
$username_exists = NULL;
$email_valid = NULL;
$passwords_match = NULL;
$password_acceptable = NULL;
$password_long_enough = NULL;
$password = NULL;
//Prepare Statements
//Check for Username Existing Statement
$check_username_match = $connect->stmt_init();
$sql_check_username = "SELECT id FROM $tablename WHERE username=?";
$check_username_match->prepare($sql_check_username);
$check_username_match->bind_param("s", $username);
//Insert Into Table Statement
$register_query = $connect->stmt_init();
$sql_register = "INSERT INTO $tablename (username, email, password, token, active, level) VALUES (?, ?, ?, ?, ?, ?)";
$register_query->prepare($sql_register);
$register_query->bind_param("sssssi", $username, $email, $hashedpassword, $token, $activated, $level);
//Execute When Form Submitted
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$email = mysqli_escape_string($connect, $_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
//Check if Username Exists
$check_username_match->execute();
$check_username_match->store_result();
$numrows = $check_username_match->num_rows;
if ($numrows==0){
$username_exists = false;
} else {
$username_exists=true;
}
//Check if Passwords Match
if ($password==$confirm_password){
$passwords_match = true;
} else {
$passwords_match = false;
}
//Check if Email Address is Valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_valid = true;
} else {
$email_valid = false;
}
//Check if Passwords Contains Special Characters
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
//Check if Password is Long Enough
$password_length = strlen($password);
if ($password_length>8){
$password_long_enough = true;
} else {
$password_long_enough = false;
}
//Validate Password
if(!$uppercase || !$lowercase || !$number || !$password_long_enough || $password = '') {
$password_acceptable = false;
} else {
$password_acceptable = true;
}
//Register if all Validations Met
if(!$username_exists && $email_valid && $passwords_match && $password_acceptable){
//$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$token = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$activated="No";
$level = 0;
$hashedpassword = password_hash($password, PASSWORD_DEFAULT);
$register_query->execute();
$message = "Hello, welcome to the site.\r\n\r\nPlease click on the following link to activate your account:\r\nlocalhost/login_system/activate.php?token=".$token;
mail($email, 'Please Activate Your Account', $message);
header("Location: login.php");
}
}
?>
UPDATE: I changed my above code to reflect the changes I made with password_hash. However, the problem still persists.
This is my login php:
<?php
include("connection.php");
session_start();
//Reset Variables
$message = '';
$location = "/login_system/index.php"; //default location to redirect after logging in
$username = '';
$password = '';
//Check to see if user is newly activated; if he is display a welcome message.
if(isset($_GET['activated'])){
if($_GET['activated'] == "true"){
$message = "Thank you for verifying your account. Please login to continue.";
}
}
//Check to see if user is coming from another page; if he is then store that page location to redirect to after logging in.
if(isset($_GET['location'])) {
$location = htmlspecialchars($_GET['location']);
}
echo $location;
//Prepare login check statement
$check_login = $connect->stmt_init();
$sql = "SELECT id, password FROM $tablename WHERE username=?";
$check_login->prepare($sql);
$check_login->bind_param("s", $username);
//Execute Login Check
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$password = $_POST['password'];
$check_login->execute();
$check_login->store_result();
$numrows = $check_login->num_rows;
$check_login->bind_result($id, $match);
$check_login->fetch();
if ($numrows==1 && password_verify($password, $match)) {
$_SESSION['login_user'] = $id;
$goto = "localhost".$location;
header("location: $goto");
$message = "Success!";
} else {
$message="Username or password is not valid."."<br>".$match."<br>";
}
}
$connect->close();
?>
You should just feed the password you want to hash into PHP's password_hash();function. Like so...
$password = $_POST['password'];
$options = [
'cost' => 12,
];
echo password_hash($password, PASSWORD_BCRYPT, $options);
Then when you want to check if the password exists in the database use password_verify(); Like so...
$password = PASSWORD_HERE;
$stored_hash = HASH_HERE;
if (password_verify($password, $stored_hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
After registration on my site the activation link sets a field 'activated' in the table to 1 from 0. So unless a user clicks on the activation link, he/she should not be able to login, but for some reason login function is still executing and activation is of no use, I have even tried the AND condition in the query but no use, can someone please help me with my code.
function login()
{
if(isset($_POST['submit']))
{
$db = new Connection(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if($username == '')
{
setMessage('Sorry you did not enter a username.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
elseif($password == '')
{
setMessage('Sorry, you did not enter a password.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
else
{
$result = $db->query('
SELECT ID, name, email, password, type, activated, suspended, count
FROM users
WHERE email = "'.$username.'"
LIMIT 1
');
$totalRows = mysql_num_rows($result);
if($totalRows == 1)
{
while($row = mysql_fetch_assoc($result))
{
if(verifyPassword($password, $row['password']) == TRUE)
{
if($row['activated'] == 0)
{
setMessage('You have not activated your account.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
if($row['suspended'] == 1)
{
setMessage('Your account is suspended. You may request to have your account restored by sending us a message on the Contact us page of newtongrads.com.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
if($row['type'] != 'ADMIN')
{
setMessage('You don\'t have enough privileges to access this page.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
else
{
$_SESSION['admin']['sessionID'] = base64_encode(date('Ymdhis'));
$_SESSION['admin']['userID'] = $row['ID'];
$_SESSION['admin']['email'] = $row['email'];
$_SESSION['admin']['type'] = $row['type'];
$_SESSION['admin']['fullName'] = getName($row['ID']);
$_SESSION['admin']['profileImage'] = $row['ID'];
setcookie('username', $username, time() + (86400 * 7));
//setcookie('password', $password, time() + (86400 * 7));
//$row['type'];
$query = 'UPDATE users
SET count = "'.($row['count']+1).'"
WHERE ID = "'.$row['ID'].'"';
$db->query($query);
setMessage('Successfully logged in.', 1);
header('Location: '.BASE_URL.'dashboard/home');
exit;
}
}
else
{
setMessage('Sorry, you have entered an incorrect password.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
}
}
else
{
setMessage('Sorry, no user exists with that username.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
}
}
}
use this code
this should work
<?php
function login()
{
if(isset($_POST['submit']))
{
$db = new Connection(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if($username == '')
{
setMessage('Sorry you did not enter a username.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
elseif($password == '')
{
setMessage('Sorry, you did not enter a password.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
else
{
$result = $db->query('
SELECT ID, name, email, password, type, activated, suspended, count
FROM users
WHERE email = "'.$username.'"
LIMIT 1
');
$totalRows = mysql_num_rows($result);
if($totalRows == 1)
{
while($row = mysql_fetch_assoc($result))
{
if(verifyPassword($password, $row['password']) == TRUE)
{
$activated = $row['activated'];
if($activated == 0)
{
setMessage('You have not activated your account.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
if($row['suspended'] == 1)
{
setMessage('Your account is suspended. You may request to have your account restored by sending us a message on the Contact us page of newtongrads.com.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
if($row['type'] != 'ADMIN')
{
setMessage('You don\'t have enough privileges to access this page.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
else
{
$_SESSION['admin']['sessionID'] = base64_encode(date('Ymdhis'));
$_SESSION['admin']['userID'] = $row['ID'];
$_SESSION['admin']['email'] = $row['email'];
$_SESSION['admin']['type'] = $row['type'];
$_SESSION['admin']['fullName'] = getName($row['ID']);
$_SESSION['admin']['profileImage'] = $row['ID'];
setcookie('username', $username, time() + (86400 * 7));
//setcookie('password', $password, time() + (86400 * 7));
//$row['type'];
$query = 'UPDATE users
SET count = "'.($row['count']+1).'"
WHERE ID = "'.$row['ID'].'"';
$db->query($query);
setMessage('Successfully logged in.', 1);
header('Location: '.BASE_URL.'dashboard/home');
exit;
}
}
else
{
setMessage('Sorry, you have entered an incorrect password.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
}
}
else
{
setMessage('Sorry, no user exists with that username.', 0);
header('Location: '.BASE_URL.'dashboard/login');
exit;
}
}
}
}
?>
?>
I'm trying to check a table called members to see if a user exists with it's email and password. I'm able to connect to the database, but for some reason, it jumps all these if statements and echoes 'You have been logged in!' even when I put the wrong email or password? Here is the html and php:
<form action="/login-user" method="POST">
Email: <input type="text" name="login_email"><br>
Password: <input type="password" name="login_password"><br>
<button type="submit">Login</button>
</form>
PHP:
<?php
session_start();
/*error_reporting(0);*/
require 'users/functions/user-functions.php';
require 'users/connect-database.php';
if (empty($_POST) === false) {
$email = mysqli_real_escape_string($connection, $_POST['login_email']);
$password = stripslashes(mysqli_real_escape_string($connection, $_POST['login_password']));
$encrypted_password = md5($password);
if (empty($email)) {
echo 'You need to enter an email<br>';
} else if (empty($password)) {
echo 'You need to enter a password<br>';
} else if(user_exists($connection, $email, $encrypted_password) === false) {
echo 'You don\'t seem to be registered?';
} else if (user_active($connection, $email, $encrypted_password) === false) {
echo 'You haven\'t activated your account!';
} else {
$login = login($connection, $email, $encrypted_password);
if ($login === false) {
echo 'That email/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
$_SESSION['logged_in'] = true;
echo 'You have been logged in!';
}
}
/*print_r($errors);*/
} else {
echo 'inputs were empty<br>';
}
require 'users/disconnect-database.php';
?>
Content of the file 'user-functions.php':
<?php
function sanitize($connection, $data) {
return mysqli_real_escape_string($connection, $data);
}
function logged_in() {
return $_SESSION['logged_in'];
}
function user_exists($connection, $email, $password) {
$query = mysqli_num_rows(mysqli_query($connection, "SELECT * FROM members WHERE email = '$email' AND password = '$password'"));
return ($query > 0) ? true : false;
}
function user_active($connection, $email, $password) {
$query = mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password' AND `active` = 1");
return ($query !== false) ? true : false;
}
function return_user_id($connection, $email, $password) {
return mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'");
}
function login($connection, $email, $password) {
/*$user_id = mysql_result(mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'"), 0, 'user_id');*/
/*$password = md5($password);*/
$query = mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'");
/*return (mysqli_query($connection, $query) or die (false));*/
if ($query === false) {
return false;
} else {
return $query;
}
/*return ($query !== false) ? true : false;*/
}
function log_out() {
unset($_SESSION['logged_in']);
session_unset();
session_destroy();
}
?>
If the answer is using mysql_result or mysqli_result, please explain in full detail because even after reading on the manual and W3Schools and everywhere else, I still don't understand how those functions work.
Thanks for any answers, and by the way, I have read all the other posts about this stuff but I didn't find any answers. Thanks.
First of all I would really advise to use a sha for encrypting passwords because md5 is decrypted in no time at all.
for your login function try the following:
<?php
function login($connection, $email, $password) {
$query = mysqli_query($connection, "SELECT `email`, `password` FROM `members` WHERE `email` = '$email' AND `password` = '$password'");
$count = mysqli_num_rows($query); //counting the number of returns
//if the $count = 1 or more return true else return false
if($count >= 1) {
return true;
} else {
return false;
}
}
?>
after the script has returned true you could set a session or do what you need to do with it.
EDIT You need session_start in every file so the best thing to do is include this.
I hope this works I typed it realy fast so there might be some errors in it but please let me know:
<?php
function generate($password) {
$password = hash('sha1', $password);
return $password;
}
function login($connection, $email, $password) {
$password = generate($password);
$query = mysqli_query($connection, "SELECT `email`, `password` FROM `members` WHERE `email` = '$email' AND `password` = '$password'");
$count = mysqli_num_rows($query); //counting the number of returns
//if the $count = 1 or more return true else return false
if($count >= 1) {
return true;
} else {
return false;
}
}
function exists($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$count = mysqli_num_rows($query);
if($count >= 1) {
return true;
} else {
return false;
}
}
function detail($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$associate = mysqli_fetch_assoc($query);
return $associate[$detail];
}
function errors($error) {
echo '<ul class="error">';
foreach($error as $fault) {
echo '<li>'.$fault.'<li>';
}
echo '</ul>';
}
function isLoggedIn() {
if(!empty($_SESSION['logged_in']) && exists($connection, 'id', 'members', 'id', $_SESSION['logged_in']) == true) {
return true;
} else {
return false;
}
}
function logout() {
unset($_SESSION['logged_in']);
}
if($_POST) {
$email = mysqli_real_escape_string($connect, strip_tags($_POST['email']));
$password = mysqli_real_escape_string($connect, strip_tags($_POST['password']));
if(!empty($email) && !empty($password)) {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = 'Your email: '.$email.' is not valid';
}
if(exists($connection, 'email', 'members', 'email', $email) == false) {
$error[] = 'You are not registered';
}
if(detail($connection, 'active', 'members', 'email', $email) != 1) {
$error[] = 'Your account is not activated';
}
if(empty($error)) {
$query = login($connection, $email, $password);
if($query == true) {
$_SESSION['logged_in'] == detail($connection, 'id', 'members', 'email', $email);
}
}
} else {
$error[] = 'There are empty fields';
}
if(!empty($error)) {
echo errors($error);
}
}
?>
<form action="" method="POST">
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>