Admin and User log in from two different tables - php

I was wondering if anyone could help me - I have successfully created a log in system allowing a user (student) to log in. My system also requires an admin log in, with the admin having privileges to view pages that the student does not. Both the admin and student information comes from two different tables. Below is the code I have used for the student log in (there are two different pages - users and login). I am stuck as to how to implement the admin log in. Any help is appreciated!
(Admin will log in using 'adminnum' and 'adminpassword'.
login.php
<?php
include "core/init.php";
include "includes/content.php";
if (empty($_POST) === false) {
$studentemail = $_POST ['studentemail'];
$studentpassword = $_POST ['studentpassword'];
if (empty($studentemail) === true || empty($studentpassword) === true) {
$errors[] = "You need to enter an email address and password";
} else if (user_exists($studentemail) === false) {
$errors[] = "We can't find that email address. Have you registered?";
} else {
if (strlen($studentpassword) > 32) {
$errors[] = 'Password too long';
}
$login = login($studentemail, $studentpassword);
if ($login === false) {
$errors[] = 'That email/password combination is incorrect';
} else {
$_SESSION['studentid'] = $login;
header('Location: index.php');
exit();
}
}
} else {
$errors[] = 'No data received';
}
include "includes/overall/overall_header.php";
if (empty($errors) === false) {
?>
<h2> We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
?>
<center><input id="submit" type="submit" value="Back" onclick="location.href='Login2.php'"></center>
<?php
include "includes/overall/overall_footerloggedout.php";
?>
users.php
<?php
function logged_in() {
return (isset($_SESSION['studentid'])) ? true : false;
}
function user_exists($studentemail) {
$studentemail = sanitize($studentemail);
$query = mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail`
= '$studentemail'");
return (mysql_result($query, 0) == 1) ? true : false;
}
function studentid_from_student ($studentemail) {
$studentemail = sanitize($studentemail);
return mysql_result(mysql_query("SELECT `studentid` FROM `student` WHERE `studentemail` = '$studentemail'"), 0, 'studentid');
}
`function login($studentemail, $studentpassword) {
$studentid = studentid_from_student($studentemail);
$studentemail = sanitize($studentemail);
$studentpassword = md5($studentpassword);
return (mysql_result(mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail` = '$studentemail' AND `studentpassword` = '$studentpassword'"), 0) == 1) ? $studentid : false;
}
?>

I suggest to change your logic, extracting users and admins from two different table. Make them in only one table, but all users should contain column flag for example, where flag=1 is ADMIN and flag=0 is USER.

all i can suggest as i am not a php coder but have done some in the past is to add another field in your database where you will set levels of privileges for users (0 for normal members, 1 for admin). After you have done that just add it to your users script through php coding which i barely know. Hope that helps a little bit.

Related

Login count in php

I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.php');
}
}
?>
`

Forgotten password page help [PHP/HTML]

I have a CMS, I am creating a forgotten password page, the page will require a user to enter an email address and the code will find it in the database and send them an email, in my database, i have multiple users accounts assigned to one email address.
I want it so that if the user enters an email address and it was more than one account assigned to it, to error a message saying please contact your admin, but atm, it is not doing this. Any suggestions?
Here is my forgotten password page code:
if ($lookup) {
$user->sendPasswordResetEmail();
echo"sent email";
} elseif ($lookup) {
echo "please contact your admin";
}else{
$echo"Can't find user";
}
}
}else{
echo "please enter an email address";
}
}
I take the information from a different file, here is the snippet for the code where I take the database:
$resetsystem = $db->query($qry);
if ($resetsystem && $resetsystem->num_rows == 1) {
$that->setUserData($rs->fetch_assoc());
return true;
}
if ($resetsystem && $resetsystem->num_rows > 1) {
return;
}
return false;
}
update following code:
function lookupByEmail($userID) {
global $db;
$this->id = $userID; $qry = " SELECT user_id, user_first_name, user_last_name, user_username, user_email, user_suspended FROM cms_users WHERE user_email = " . $db->SQLString($this->id) . " AND user_deleted
= 0;";
$rs = $db->query($qry);
if ($rs && $rs->num_rows == 1) {
$this->setUserData($rs->fetch_assoc());
return 1;
}
if ($rs && $rs->num_rows > 1) {
return 2;
}
return 0;
}
and then where you are checking the $found variable do these updates
if ((int)$found == 1) {
$user->sendPasswordResetEmail();
$str_Message = '<div class="success_message">User found, an email has been dispatched to you.</div>';
} elseif ((int)$found > 1) {
$errors->defineError("too_many_users", "please contact your admin", array());
}else{
$errors->defineError("user_not_found", "The specified user could not be found. Please try again.", array());
}

Doesnot receive an error

I've an member system now I've made when somebody register an account, he need to activate it by his email. He will receive an valid link in his inbox So for example:
activate.php?email=ipoon2#outlook.com&email_code=b5b90ae21e31229878d681680db16bdf This link is valid so when I go to this link, he activates the account succesfully.
You see after ?email= ipoon2#outlook.com So when I change that into ipodn2#outlook.com and the email_code is still the same, he cannot activate his account. He needs to receive an error like We cannot find that email, and when he changes the email_code He will receive an error like this problem activate your account
Thats the problem what I've got When I change the email I don't receive any error. Neither for email_code
I've a file that is called activate.php which this code is including:
<?php
} else if (isset($_GET['email'], $_GET['email_code']) === true) {
$email = urldecode(trim($_GET['email']));
$email_code = trim($_GET['email_code']);
$user = new User();
if(User::email_exists($email) === false) {
echo 'We cannot find that email'; // return error doesn't show up
} else if (User::activate($email, $email_code) === false) {
echo 'problem activate your account'; // return error doesn't show up
}
}
?>
Also I've 2 functions made, there are in the class file User.php
public function email_exists($email) {
require './config.php';
$email = urldecode(trim($_GET['email']));
$sql_30 = $db->query("SELECT COUNT(id) FROM users WHERE email = '$email'");
if ($sql_30->fetch_object() === true) {
return true;
} else if ($sql_30->fetch_object() === false) {
return false;
}
}
public function activate($email, $email_code) {
require './config.php';
$email = urldecode($email);
$email_code = $db->real_escape_string($email_code);
$sql_33 = $db->query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `group` = 0");
if ($sql_33->fetch_object()) {
$db->query("UPDATE `users` SET `group` = 1 WHERE `email` = '$email' AND `email_code` = '$email_code'");
return true;
} else {
return false;
}
}
To me, your email_exists() and activate() are wrong.
if ($sql_30->fetch_object() === true) {
return true;
} else if ($sql_30->fetch_object() === false) {
return false;
}
From the php documentation of mysqli_result::fetch_object :
Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset. So your test must be :
if ($sql_30->fetch_object() !== NULL) {
return true;
}
return false;
I guess it should solve your problem.

Help on how to continue with code that verifies a registered user and updates mySQL

When a user registers, the script sends an email to verify his account. Clicking on the link, the script gets the token
$token = mysql_real_escape_string($_GET["token"]);
and what I thought to do is
if($token != '') {
mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
}
or
if($token != '') {
$result = mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
if($result) { }
else { }
}
What is my purpose is to echo a success or failed message on the user. When it will be success then the verified will be empty.
What is the appropriate way of doing this with my examples above?
Should I check if there is the token in the DB before updating it?
Thank you.
Your current method updates a record if it exists but does not take into account that which does not exist or match. You should run something similar to:
if($token != '') {
$result = mysql_query("SELECT COUNT(*) FROM members WHERE verified = '$token'");
while($row = mysql_fetch_row($result)) {
$records = $row[0];
}
if($records == 0) { echo 'no results'; }
elseif($records ==1) { echo 'you matched'; then update the record. }
}
edit
changed BACK to the while loop, wasn't thinking of the count returning 0 rows

Php login panel

I have developed a small application. I created a login panel for it. I have only one user so, I hard coded both user name and password. Below is the code but it is not working.I don’t have any db for this bcoz, it will have only 1 user.
Any help ii be appreciated.
Thanks in advance.
<?php
if(($_POST['na'] = 'admin') == ($_POST['pwd'] = 'zucker'))
{
header("location:first.php");
}
else
{
header("location:index.php?msg=enter correct user name and password");
}
?>
ok, from what I can decipher from your code - you have = and == applied incorrectly. Where you have = you want == and where you have == you want &&
if (($_POST['na']=='admin') && ($_POST['pwd']=='zucker')) {
header('location:first.php')
};
I hope this isn't how your login model is going to work - whats to stop just anyone going directly to first.php?
To avoid some Notice errors and other bugs:
<?php
$na = isset($_POST['na']) ? $_POST['na'] : false;
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : false;
$submit = isset($_POST['submit']) ? true : false;
if ($submit) {
if ($na == 'admin' && $pwd == 'zucker') {
header("location:first.php");
exit(); // Make sure nothing else gets sent
} else {
header("location:index.php?msg=enter correct user name and password");
exit(); // Make sure nothing else gets sent
}
}
?>
Here's a slightly more advanced example:
<?php
$na = isset($_POST['na']) ? $_POST['na'] : false;
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : false;
$submit = isset($_POST['submit']) ? true : false;
// Accounts array (append as you wish)
$accounts = array(
'admin' => '4635c0015b2084afcc7cb39593545e06',
'foo' => '37b51d194a7513e45b56f6524f2d51f2'
);
// form complete?
if ($submit && $na && pwd) {
if (isset($accounts[$na]) && md5($accounts[$na]) == $pwd) {
header("location:first.php");
exit(); // Make sure nothing else gets sent
} else {
header("location:index.php?msg=enter correct user name and password");
exit(); // Make sure nothing else gets sent
}
}
?>

Categories