Im creating a website where users can login to buy books and collect them from store. I have a login screen where both normal users as well as staff use to login. However im trying to find a way to differentiate between normal users and staff.
I have a table called "users" where one of the columns is called "account_type" which can hold a value of U for normal user and A for admin.
this is the code i currently have:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$query = mysqli_query($mysqli, "SELECT * FROM users where Username='$user' AND Password='$pass'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
header("location: home.php"); // Redirecting To Other Page
}elseif ($rows["account_type"] == "A"){
header ("location: adminHome.php");
}else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
Line 24-30 is where ive put the check but it doesnt seem to work.
I dont get any errors it just skips to the validation part when i try the admins login details and says "username or password is invalid" It does login as the normal user however.
Any ideas?
$rows = mysqli_num_rows($query);
if ($rows == 1) {
header("location: home.php"); // Redirecting To Other Page
}elseif ($rows["account_type"] == "A"){
...
}
Take a closer look at this. You are setting $rows with mysqli_num_rows, it will not be an array and should only be an integer. You need to use a fetch function to get the column data. The fetch would be run using the MySQLi statement variable (in your case the return value of mysqli_query or $query. Read more about fetch here: http://php.net/manual/en/mysqli-stmt.fetch.php
P.S. Your code a little messy. You use stripslashes then real escape, why not use prepared statements? They are safer and more efficient because they let the DBMS (MySQL) handle the variables. Read more about prepared statements here: http://php.net/manual/en/mysqli.prepare.php
Related
I'm just learning the PHP basics and I need to create a blog. I've followed a few tutorials but I can't seem to be able to get PHP to recognize when I've pressed the login form I created with HTML.
<?php
session_start(); //keep a session open so no need to relogin
if(isset($_POST['submit'])){ //check to see if submit button is pressed
$user = $_POST['username'];
$pwrd = $_POST['pwrd'];
//add database connection
include('./includes/db_connect.php');
if(empty($user) || empty($pwrd)){
echo 'Please ensure both password and username fields are filled.';
}else{
$pwrd = md5($pwrd);
$query = $db->query("SELECT user_id, username FROM user WHERE username='$user' AND password = '$pwrd'"); //grab username and password from table
if($query->num_rows ===1) {
while ($row = $query->fetch_object()) {
$_SESSION['user_id'] = $row->user_id;
}
header('Location : index.php'); //redirt user to index.php
exit();
}else{
echo 'Wrong credentials';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="container">
<form action="login.php" method="post">
<p>
<label>Username</label><input type="text" name="username" />
</p>
<p>
<label>Password</label><input type="password" name="pwrd" />
</p>
<input type="submit" value="LogIn" />
</form>
</div>
</body>
</html>
When I press log in while both username and password are empty I get nothing instead of 'Please ensure both password and username fields are filled.'
Any help would be appreciated.
You are checking with if(isset($_POST['submit'])){ but there is no field in the form named submit.
Try with, if ($_SERVER['REQUEST_METHOD'] === 'POST') { instead.
Or rename the submit button to submit [or something else but remember to fix the check as well]
$_POST data comes from the 'name="..."' item. Not type="...". Note that simply checking if POST exists is a risky practice since you can have more than 1 form on the page, so I always use explicit checks of the desired form fields to trigger form handlers.
<?php
session_start(); //keep a session open so no need to relogin
if(isset($_POST['username'])){ //check to see if submit button is pressed
$user = $_POST['username'];
$pwrd = $_POST['pwrd'];
//add database connection
include('./includes/db_connect.php');
if(empty($user) || empty($pwrd)){
echo 'Please ensure both password and username fields are filled.';
}else{
$pwrd = md5($pwrd);
$query = $db->query("SELECT user_id, username FROM user WHERE username='$user' AND password = '$pwrd'"); //grab username and password from table
if($query->num_rows ===1) {
while ($row = $query->fetch_object()) {
$_SESSION['user_id'] = $row->user_id;
}
header('Location : index.php'); //redirt user to index.php
exit();
}else{
echo 'Wrong credentials';
}
}
}
?>
This seems like it should be simple, but I've tried it every which way and can't seem to get it to work.
I have this login script which I adapted from an online tutorial. What I'd like to do is have users sign in with a username and password, and if these are correct, have it go after their lab results in another table (same database) and display them. I can get it to sign in, but that's it. Here's the login code:
<?php //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
/*This is where I'm assuming the new query needs to go.
Query a different table named "data" and pick out information according to
$username which was put in earlier */
echo "<br><a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div><?php }
?>
</body>
</html>
A "Join" is what I get when I google it but that doesn't seem right. Could someone help?
You can just use a different query for making it easy:
$sql = mysql_query("SELECT * FROM data WHERE user = '" . mysql_real_escape_string($username) . "'");
Then you can process with this.
Please note that you should not use MySQL driver as it is deprecated, use MySQLi(mproved) instead. And you should escape the POSTed values, this is very important!
Your last else statement is trying to echo the HTML.
You should be using mysqli or PDO since mysql is deprecated.
<?php //Start the Session
session_start();
// require('connect.php');
// Establish connection with database
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `people` WHERE username='$username' and password='$password'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
echo "Valid";
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
echo "Username: $username";
echo "Session Username:".$_SESSION['username'];
// This is where I'm assuming the new query needs to go.
// Query a different table named "data" and pick out information according to $username which was put in earlier
echo "
Logout";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="test.php" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div>
</body>
</html>
I have a database table that holds a users username, password and other information as well as whether theyre and administrator or not. Its currently set to Char where A is for admin and U is for normal user.
I have the following code which checks if a user exists:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if(mysqli_num_rows($result) == 1) {
header("Location: home.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
</html>
How would i check if Account_Type is A and if so direct the user to another page instead of the normal home.php page?
EDIT:
It works fine however the admin wont log in.
Ive given it test username of 456 and a password of 456 when i enter them into the two textboxes nothing happens, the screen just refreshes and im back on the login page:
new code below:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
//set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
You are going about this the wrong way. Every page that requires the user to be authenticated should check at the very start if the user is authenticated and at what level. The way to do that is to use the session.
Right now you are setting the session variable before you even check whether the user / password combination is correct so you are effectively logging in anybody who enters a username.
You need to store the variables in the session only upon successful login and as mentioned you need to get a row from your result set to get the user information:
// Personally I would use a prepared statement here
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
// Now you can set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
// Add any additional user information to the session that you might need later on
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
Now in every page where a user is required you can do:
session_start();
if (isset($_SESSION['Username']))
{
// valid user, additional checks for user type?
}
else
{
// not a valid / logged in user
}
Note:
(unsalted...) md5 is unsafe to use for passwords, see Secure hash and salt for PHP passwords;
$row = mysqli_fetch_array($result);
if ($row['Account_Type'] === 'A') {
} elseif ($row['Account_Type'] === 'U') {
} else {
}
I am designing a website which have four modules Admin, branch admin, reporter, accountant where each of the respective person can login to their respective page like admin will login to the admin page and reporter will login to it's page, but the code is not working.
When I try login to any module it login only to the admin page and does goes to the branch admin or reporter or accountant.
This is my index.php page
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user']))
{
header("Location: admin.php");
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>LoginIN</title>
<link href="styles/bootstrap.min.css" rel="stylesheet">
<link href="styles/signin.css" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<header id="top">
<center><h1>Reporter Management System</h1></center>
<div class="container">
<form class="form-signin" role="form" action ="" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="email" name="username" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<br>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me">Remember me
<br>
</label>
</div>
<input name="submit"button class="btn btn-lg btn-primary btn-block" type="submit" value=" Sign in">
<span><?php echo $error; ?></span>
<br>
Forgot your password?
</body>
</html>
This is my login.php page
<?php
error_reporting( E_ALL );
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$usr=$_POST['username'];
$pwd=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$con = mysql_connect("localhost", "root1", "oec#123") or die('Error Connecting to mysql server');
// To protect MySQL injection for Security purpose
$username = stripslashes($usr);
$password = stripslashes($pwd);
$username = mysql_real_escape_string($usr);
$password = mysql_real_escape_string($pwd);
// Selecting Database
$db=mysql_select_db('rms',$con);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select username, password from login where password='$pwd' AND username='$usr'", $con) or die('Error querying database');
$rows = mysql_num_rows($query);
while ($rows = mysql_fetch_array($query)) {
$_SESSION['Sl_no']=$rows['Sl_no'];
if ($rows ==1)
{
// Initializing Session
header("location: admin.php"); // Redirecting To Other Page
}
elseif ($rows==2)
{
header("location: branchadmin.php");
}
elseif($rows==3)
{
header("location: accountant.php");
}
elseif($rows==4)
{
header("location: reporter.php");
}
else
{
$error = "Username or Password is invalid";
}
}
mysql_close($con); // Closing Connection
}
}
?>
I think the problem is with your retrieval and condition statements around this area
while ($rows = mysql_fetch_array($query)) {
$_SESSION['Sl_no']=$rows['Sl_no'];
if ($rows ==1)
{
and since the login page is redirecting to the admin.php every time, this could be because you put the number of returned rows in the $rows variable like $rows = mysql_num_rows($query); and if it is returning one row this would meet the the if ($rows ==1){header("location: admin.php");} condition you check later on...
Just an educated (and/or non-educated) guess.
Why don't you put a column in your db that indicates the users level of access. Like user_level or something where admin = 1, branchadmin = 2, accountant = 3, etc. and then do a check and re-direct based on that.
So when you check whether the username and password from the form are in the the database and if it is then you could look at their user level to see where to re-direct them.
if ($rows === 1){
$row_array = mysql_fetch_assoc($query);
if ($row_array['admin_level'] == 1){
header("location: admin.php"); // Redirecting To Other Page
}
elseif ($row_array['admin_level']==2){
header("location: branchadmin.php");
}
elseif($row_array['admin_level']==3){
header("location: accountant.php");
}
elseif($row_array['admin_level']==4){
header("location: reporter.php");
}
else{
$error = "Username or Password is invalid";
}
}
mysql_close($con); // Closing Connection
Does that make sense or am I misunderstanding what you want to achieve?
In this case, you have to use multiple session variables like $_SESSION['email'] and $_SESSION['type'].
Here, $email will be the username of particular user and $type will be the type of user like admin, branch admin, reporter, accountant etc.
These two session variables needs to be set while user is logging in.
For example, consider the following code snippet:
if(isset($_SESSION['email']))
{
if($_SESSION['type'] == "admin")
{
header('location:admin.php');
}
else if($_SESSION['type'] == "reporter")
{
header('location:reporter.php');
}
}
I have a Login Page. I am sure that the database is connected, but when I submit the form, the page refreshes and nothing happens.
May I please know what's wrong here? I cant seem to fix it. =(
<?php
session_start();
require_once('common/config.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM `users` WHERE username='$username' and password='$password'";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count == 1)
{
$_SESSION['username'] = $username;
header("location: adminhomepage.php");
}
else
{
echo "Invalid Login Credentials.";
}
}
?>
Here is my form.
<html>
<head>
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
<link rel="icon" href="images/favicon.ico" type="image/x-icon">
<title>
XXX
</title>
<link rel="stylesheet" href="login.css">
</head>
<body>
<img id= "loginlogo" src="images/loginlogo.png" alt="XXX">
<h1 id = "loginmain">
XXX
</h1>
<br>
<div id= "inputs">
<form id ="loginform" action="login.php" method="post">
<h2 id = "loginheading">
LOGIN
</h2>
<hr id ="loginline">
<br>
<input id="username" type="text" placeholder="Username" autofocus required>
<br><br>
<input id="password" type="password" placeholder="Password" required>
<br><br>
<input id="loginbutton" type="submit" value="Login">
</form>
</div>
</body>
</html>
You have not set names on your HTML input (username/password). You have only set an ID (ID is used for assigning CSS). Please add name='username' and name='password' to your input. By doing so, $_POST[username] and $_POST[password] will now contain the values posted in your form.
Ergo, your current code says: If $_POST[username] is set, do this. And if it is not set, nothing happens (ergo the blank page). Try adding this after your last } before making my suggested changes:
else {
echo "SESSION[username] is not set";
}
Im guessing this will give you the message "SESSION[username] is not set" instead of a blank page?
When debugging, it is sometimes useful to print the received values for $username and $password using echo(). Maybe you will find that one of the POST[] elements is not being sent properly. Posting login form would be useful.
First, there are some important changes what you need to know:
Do not use mysql functions, use mysqli or PDO instead, bacuase mysql functions are deprecated.
Always avoid about sql injections! Escape your strings, they are came from a form.
You do not need to create $username and $password variable, if you do not use them later or do not want to manipulate them. Simply use the $_POST["username"] and $_POST["password"] directly.
Do not store clear text passwords in your database. Use a crypt algorithm like md5, and compare the value of your table with the crypted password.
You can also try to debug your code, before you redirect your page. So when you are debug, comment out the header("Location ..."); line, and dump your sql.
So your code should seems like this, when you debugging:
session_start();
require_once('common/config.php');
if (isset($_POST['username'])) {
$sql = "SELECT * FROM `users` WHERE username='".mysqli_real_escape_string($link, $_POST["username"]). "'"
. " AND password='".md5($_POST["password"]). "'";
echo $sql; //Here you can see, what your $sql has, and you can paste it directly into your CLI or phpMyAdmin, etc...
$result = mysql_queryi($link, $sql) or die(mysqli_error($link));
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['username'] = $_POST["username"];
header("location: adminhomepage.php");
} else {
echo "Invalid Login Credentials.";
}
}