Booleans SQL and PHP validation - php

I have a column in a table (users) called admin and its datatype is boolean. Two users are set to "true"
My objective is when those two log in, they have acess to the back office, but so far the code isn't working:
<?php
session_start();
$error="";
$successMessage="";
if ($_POST){
if(!isset($_POST["salada"]) || $_POST["salada"]===""){
$error = "PHP: An email is required <br>";
}
if(!isset($_POST["arroz"]) || $_POST["arroz"]===""){
$error .= "PHP: A password is required";
}
if ($error !=""){
$error = '<div class="error-login">'.$error.'</div>';
}else {
require("MGconfig.php");
$email = mysqli_real_escape_string($connection, $_POST["salada"]);
$pwd = md5(mysqli_real_escape_string($connection, $_POST["arroz"]));
$result = mysqli_query($connection, "select name, id from users where email = '".$email."' and password = '".$pwd."'");
if (mysqli_num_rows($result) !==1){
$error='<div class="error-login">PHP: Invalid email or password</div>';
header("Location:index.php?error=".$error);
}else {
$nome = mysqli_fetch_row($result);
$_SESSION["name"] = $nome[0];
$_SESSION["id"]=$nome[1];
header ("Location: main.php");
}
}
}
?>
<?php
if($_SESSION['admin'] !=0){
header ("Location:admin.php");
}?>
Can someone tell me why isnt working? Is Syntax? If I compara the field "name", the restriction works...Thanks in advance!

The problem is, you haven't selected admin column in the SELECT query, you have only selected id and name columns. Plus, there's nowhere you're checking whether the logged in user is admin or not.
So the solution is, select the admin column in your SELECT query and make use of that column value to check whether the logged in user is admin or not, like this:
// your code
$result = mysqli_query($connection, "select name, id, admin from users where email = '".$email."' and password = '".$pwd."'");
if (mysqli_num_rows($result) !== 1){
$error='<div class="error-login">PHP: Invalid email or password</div>';
header("Location:index.php?error=".$error);
}else{
$nome = mysqli_fetch_row($result);
$_SESSION["name"] = $nome[0];
$_SESSION["id"] = $nome[1];
if($nome[2]){
// logged in user is admin
$_SESSION["admin"] = true;
}else{
// logged in user is not admin
$_SESSION["admin"] = false;
}
header ("Location: main.php");
exit();
}
// your code
Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.

Related

PHP/MYSQL: Login with multiple types of users

I want to create a login page for admin and super admin in one PHP page. Currently, I do login page for admin and super admin separately but use the same database table.
Below is my current code for admin and super admin login
admin_login.php
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$Email = mysqli_real_escape_string($link,$_POST['Email']);
$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT staff.Email FROM staff WHERE Email = '$Email' AND Pwd ='$Pwd' AND staff.Role = 'admin'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $Email;
header("location: pages/dashboard/dashboard_admin.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
super_admin_login.php
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$Email = mysqli_real_escape_string($link,$_POST['Email']);
$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT staff.Email FROM staff WHERE Email = '$Email' AND Pwd ='$Pwd' AND staff.Role = 'super_admin'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $Email;
header("location: pages/dashboard/dashboard_super_admin.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
can anyone help me? Really appreciate
What you are doing now is to check if there is any username and password with the specific role, why not checking username and password and after that check the role of it to redirect to correct place ?
You can merge them, What you should do is to first check username and password and after that check the role to see if it is Admin or Super Admin to redirect to correct dashboard.
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$Email = mysqli_real_escape_string($link,$_POST['Email']);
$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT staff.Email,staff.Role FROM staff WHERE Email = '$Email' AND Pwd ='$Pwd'"; // Remember You do not need to check role here so you can accept both
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $Email;
if($row["Role"] == "admin"){ //Check the role here
header("location: pages/dashboard/dashboard_admin.php");
}else{ // If you want to be more specific you can write a else-if here too.
header("location: pages/dashboard/dashboard_super_admin.php");
}
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
PS: NEVER STORE PLAIN PASSWORD AND USE PREPARED STATEMENTS TO PREVENT SQL INJECTION
You are approaching this from slightly the wrong perspective. Every user should login through the same script. User presents a UserId (Email in your case) and Password, you check they are correct and THEN you pick up the staff.Role to know what kind of user they are, and treat them accordingly
I have also changed your code to use a prepared, parameterised and bound query
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
//$Email = mysqli_real_escape_string($link,$_POST['Email']);
//$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT Pwd, Role
FROM staff
WHERE Email = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param('s',$_POST['Email']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($result->num_rows == 1 )
// this should really be using `password_verify()`
// but as that requiesa change to the way you save the password
// I cannot just add it here
if ( $_POST['Pwd'] == $row['Pwd'] ){
$_SESSION['login_user'] = $Email;
// might be useful to put the role in the session for later use as well
$_SESSION['Role'] = $row['Role'];
if ($row['Role'] == 'admin')
header("location: pages/dashboard/dashboard_admin.php");
exit;
}
if ($row['Role'] == 'super_admin')
header("location: pages/dashboard/dashboard_super_admin.php");
exit;
}
} else {
$error = "Your Login Name or Password is invalid";
}
}
}
?>
Additional reading to change your code to use the more secure password_hash() and pasword_verify()

php user login script

<?php
if(isset($_POST['submit'])) {
$UserName = mysql_real_escape_string($_POST['UserName']);
$password = mysql_real_escape_string($_POST['password']);
$checkbox = isset($_POST['remember_me']);
if(user_exists ($UserName, $db_connect)) {
$result = mysqli_query ($db_connect, "SELECT password FROM users WHERE UserName = '$UserName'");
$retrievepassword = mysqli_fetch_assoc($result);
if(md5($password) !== $retrievepassword['password']) {
$alert = "Invalid Password";
} else {
$_SESSION['UserName'] = $UserName;
if($checkbox == "on") {
setcookie("UserName", $UserName, time()+3600);
}
header("location: profile.php");
}
} else {
$alert = "Username doesn't exit in database";
}
}
?>
I've made the following login script which is working fine and now I want to check the user's status before login, if user is active, it will login and if it's request is pending or rejected, it will display an error.
I've done the 1st part and confused about the other part where I've to check for the status.
Can anybody help me according to my code?
I am assuming that you have a column in your DB that stores the user's status.
Sooo .. The answer to your question is, after checking if the username is existing in you DB, check if the status is "active" or not. If no, then just display the error message.
You may think of another way to query your data, like:
SELECT * FROM USERS WHERE USERNAME = 'username' AND PASSWORD = 'password' AND STATUS = true
So that you can determine right away if it is active or not if it does not return anything.
I hope this helps. :)
You can check status after checking valid password and return appropriate message. Try below code :
if(user_exists ($UserName, $db_connect))
{
$result = mysqli_query ($db_connect, "SELECT password,status FROM users WHERE
name = '$UserName'");
$retrievepassword = mysqli_fetch_assoc($result);
if(md5($password) !== $retrievepassword['password'])
{
$alert = "Invalid Password";
}
else
{
//check Status
if($retrievepassword['status'] == 1) //whatever condtion to match
{
$_SESSION['UserName'] = $UserName;
if($checkbox == "on")
{
setcookie("UserName", $UserName, time()+3600);
}
header("location: profile.php");
}
else
{
$alert = "User Not active"; //Message to display
}
}
}
else
{
$alert = "Username doesn't exit in database";
}
There are two ways :
Either add condition in your where to check whether user is active
or not.
Or, once you validated user for correct user/password, then
validate through if condition and navigate to correct page
accordingly.
Also, correct your SQL to use prepared statement.
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE
UserName = ? AND password = ?');
$stmt->bind_param('s', $UserName);
$stmt->bind_param('s', md5($password));
$stmt->execute();
First of all, I would like to point out that you have used $ _SESSION without starting the session. To do this you have to write
session_start();
at the beginning of the code.
To verify that the user is logged in, write this just under session_start():
if(isset($_SESSION['UserName']) or isset($_COOKIE['UserName'])){
header("location: profile.php");
}
If you do not know how to check in profile.php if the user is logging in here is how to do it:
PS: I suggest you create a check.php file so that you just include it in the pages reserved for logged in users.
check.php
if(!isset($_SESSION['UserName']) or !isset($_COOKIE['UserName'])){
// Redirect to login or enter what you want to happen if the user is not logged in
}

php register form not updating database

So when I sign into my website with existing DB credentials, it logs in perfectly, redirects me to a Welcome.php page and where "Login/register" text usually sits, it now displays the username there, similar to this:
welcome (username) Logout.
Now that all works great. But here is my problem:
I have a register script that once submitted, also redirects me to my Welcome.php page upon a successful registration. BUT the "Login/register" text does not change, (essentially meaning no one is logged in) AND when i check my database, there are no new entries.
To confirm - I can fill out my signup sheet and click "Signup", then i'm redirected to a Welcome.php page... but nothing has changed (no new credentials stored in the db and nothing other than a page redirect)
My new_signup.php script is as follows:
<?php
include "scripts/connection.php";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$myusername = mysqli_real_escape_string($link,$_POST['Username']);
$myname = mysqli_real_escape_string($link,$_POST['Name']);
$mypassword = mysqli_real_escape_string($link,$_POST['Password']);
$myemail = mysqli_real_escape_string($link,$_POST['Email']);
$myaddress = mysqli_real_escape_string($link,$_POST['Address']);
$mypostcode = mysqli_real_escape_string($link,$_POST['Postcode']);
//Checks the database to see if username exists already
$query = "SELECT * FROM Customer WHERE Customer_Username = '$myusername'";
$result = mysqli_query($link, $query);
$nums = mysqli_num_rows($result);
//Checks the database to see if email address exists already
$query2 = "SELECT * FROM Customer WHERE Customer_Email = '$myemail'";
$result2 = mysqli_query($link, $query2);
$nums2 = mysqli_num_rows($result2);
if ($nums >= 1)
//informs user if username already exists
echo "Username already exists, click <a href = 'user_login.php'>HERE </a> to try again";
else if ($nums2 >=1)
//informs user if email already exists
echo "Email Address already exists, click <a href = 'user_login.php'>HERE </a> to try again";
else {
$insert = 'INSERT INTO Customer
(Customer_Username, Customer_Name,
Customer_Password, Customer_Email, Customer_Address,
Customer_Postcode)
VALUES("'.$myname.'","'.$myusername.'","'.$mypassword.
'","'.$myemail.'","'.$myaddress.'","'.$mypostcode.'")';
mysqli_query($link, $insert);
mysqli_close($link);
if($insert) {
$_SESSION['message'] = "Registration Successful";
header("Location: /Welcome.php");
} else {
$_SESSION['message'] = "Something went wrong";
}
}
}
?>
So what I need to happen is for a user to sign up, be redirected to the welcome.php page and for credentials to be stored in the DB. There are also checks to see if emails/usernames already exist.
Just to add, my login.php script and the above new_signup.php are separate php files. Not sure if doing it my way is easier than keeping both the login and signup scripts in one file
I have triple checked all of my DB fields are correct along with the form fields too.
Happy to provide more details if needed.
Thank you for your time.
UPDATE
I have updated the code to show {} and added in some suggested comments, All i get know when I click signup is a white screen.
<?php
include "scripts/connection.php";
error_reporting(E_ALL);
ini_set('display_errors', 1);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$myusername = mysqli_real_escape_string($link,$_POST['Username']);
$myname = mysqli_real_escape_string($link,$_POST['Name']);
$mypassword = mysqli_real_escape_string($link,$_POST['Password']);
$myemail = mysqli_real_escape_string($link,$_POST['Email']);
$myaddress = mysqli_real_escape_string($link,$_POST['Address']);
$mypostcode = mysqli_real_escape_string($link,$_POST['Postcode']);
//Checks the database to see if username exists already
$query = "SELECT * FROM Customer WHERE Customer_Username = '$myusername'";
$result = mysqli_query($link, $query);
$nums = mysqli_num_rows($result);
//Checks the database to see if email address exists already
$query2 = "SELECT * FROM Customer WHERE Customer_Email = '$myemail'";
$result2 = mysqli_query($link, $query2);
$nums2 = mysqli_num_rows($result2);
if ($nums >= 1) {
//informs user if username already exists
echo "Username already exists, click <a href = 'user_login.php'>HERE </a> to try again";
}
else if ($nums2 >=1) {
//informs user if email already exists
echo "Email Address already exists, click <a href = 'user_login.php'>HERE </a> to try again";
}else{
$insert = "INSERT INTO Customer (Customer_Username, Customer_Name, Customer_Password, Customer_Email, Customer_Address, Customer_Postcode)
VALUES('$myname', '$myusername', '$mypassword', '$myemail', '$myaddress', '$mypostcode')";
}
$insertCheck = mysqli_query($link, $insert);
if($insertCheck) {
$_SESSION['message'] = "Registration Successful";
header("Location: /Welcome.php"); exit();
} else {
$_SESSION['message'] = "Something went wrong";
}
}
?>
Little edits and you might want to filter your sql queries to prevent injections:
<?php
session_start();
include "scripts/connection.php";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$myusername = mysqli_real_escape_string($link,$_POST['Username']);
$myname = mysqli_real_escape_string($link,$_POST['Name']);
$mypassword = mysqli_real_escape_string($link,$_POST['Password']);
$myemail = mysqli_real_escape_string($link,$_POST['Email']);
$myaddress = mysqli_real_escape_string($link,$_POST['Address']);
$mypostcode = mysqli_real_escape_string($link,$_POST['Postcode']);
//Checks the database to see if username exists already
$query = "SELECT * FROM Customer WHERE Customer_Username = '$myusername'";
$result = mysqli_query($link, $query);
$nums = mysqli_num_rows($result);
//Checks the database to see if email address exists already
$query2 = "SELECT * FROM Customer WHERE Customer_Email = '$myemail'";
$result2 = mysqli_query($link, $query2);
$nums2 = mysqli_num_rows($result2);
if ($nums >= 1)
//informs user if username already exists
echo "Username already exists, click <a href = 'user_login.php'>HERE </a> to try again";
else if ($nums2 >=1)
//informs user if email already exists
echo "Email Address already exists, click <a href = 'user_login.php'>HERE </a> to try again";
else {
$insert = 'INSERT INTO Customer
(Customer_Username, Customer_Name,
Customer_Password, Customer_Email, Customer_Address,
Customer_Postcode)
VALUES("'.$myname.'","'.$myusername.'","'.$mypassword.
'","'.$myemail.'","'.$myaddress.'","'.$mypostcode.'")';
$insertCheck = mysqli_query($link, $insert);
mysqli_close($link);
if($insertCheck) {
$_SESSION['message'] = "Registration Successful";
header("Location: /Welcome.php");
} else {
$_SESSION['message'] = "Something went wrong";
}
}
}
header("Location: /registerview.php");//-->assuming your registration view
?>
Change
$insert = 'INSERT INTO ... VALUES ("'.$myname.'", ...
to
$insert = "INSERT INTO ... VALUES ('".$myname."', ...
(switching single for double quotes and vice versa)

Setting an admin page using sessions and type in sql database?

I have created a website with a functioning login system and in my database in the users table there is a column names type with either standard or admin. I have created a page for the admin only to edit products etc however i'm stuck on how to set it so only the 'admin' can view the page instead of just anyone that is logged in. Heres what I have so far?
admin.php
<?session_start(); ?>
<?php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if($_SESSION['type'] = 'admin'){
//admin content here
{
<?php
if ($_SESSION['type']) = 'standard')
{
echo 'you must be an admin to see this page';
}
?>
loginaction.php
<?php
session_start();
include'connection.php';
$email = trim($_POST["email"]);
$password = trim($_POST["password"]);
$password=md5($_POST["password"]);
if (empty($email) or empty($password)) {
header("Location: homepage.php?form=invalid"); //Redirection information
exit;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
header("Location: homepage.php?email=invalid");
exit;
}
$query = "SELECT * FROM users WHERE email= '$email' AND password = '$password' ";
$result = mysqli_query($connection, $query) or exit("Error in query: $query. " . mysqli_error());
if ($row = mysqli_fetch_assoc($result)) {//Then we have a successful login
$_SESSION["authenticatedUserEmail"] = $email;
$_SESSION['ID'] = $row['ID'];
$_SESSION["password"] = $row['password'];
header("Location: homepage.php");
} else {//Login was unsuccessful
echo "User does not exist";
header("Location: login.php?user=invalid");
}
?>
You are not using comaprisons instead setting values for variables in the conditions where you check for the user type.
if($_SESSION['type'] ='admin'){ `should be` if($_SESSION['type'] == 'admin'){
<? session_start(); ?>
<? php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if ($_SESSION['type'] == 'admin') {
//admin content here
}
if ($_SESSION['type']) == 'standard') {
echo 'you must be an admin to see this page';
} ?>
There are other errors in the code such as not putting the curly braces to end the statements correctly. This code should work, however it is a very unsafe code as anyone with sql injection and good programming knowledge will "tear" your website apart and worse, they steal and manipulate your data.
You should use mysql_real_escape_string() to make the input from users sql injection proof to fairly high extent.
Multiple problems seems in your code too, along with the problem mentioned by #Vish in the answers:
$result = mysqli_query($query1);
Expected a connection link as first argument.
Again:
you are trying to fetch type from the user table. But using usertype in mysqli_fetch_array. Seems it is incorrect. And the $_SESSION['type'] variable is really $_SESSION['usertype'] ?
A modified code.
$query1 = "SELECT type FROM users";
$result = mysqli_query($connection, $query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['type'];
if($_SESSION['usertype'] == 'admin')
{
//admin content here
}
elseif ($_SESSION['usertype']) == 'standard')
{
echo 'you must be an admin to see this page';
}
P.S: Not sure it will solve your problem

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
}

Categories