I am having problems checking whether the user is admin or not in the database. I made it so if admin has the value 1 for the users profile then they are admin and is redirected to the admin page and if not they are redirected to the login page. However I gave my personal account the value of 1 in the database however it is still redirecting me to the login page.
I have given my code below for you to see if I have done anything wrong, please tell me as I have only just started learning PHP.
<?php
session_start();
// First we cubrid_execute(conn_identifier, SQL)te our common code to connection to the database and start the session
require("include/common.php");
$admin = $_POST['admin'];
$user = $_POST['username'];
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT *
FROM users
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($admin == 1) {
$_SESSION['username'] = $user;
header("location: memberlist.php");
}
if ($admin == 0) {
$_SESSION['username'] = $user;
header("location: login.php");
}
Correct you code First:
Try this:
if ($admin == 1) {
$_SESSION['admin'] = $admin; //put you admin in session
header("location: memberlist.php");
}
if ($admin == 0) {
$_SESSION['user'] = $user; //here put your user in session
header("location: login.php");
}
if(empty($_SESSION['user'])) //if user is empty then it redirects to login page
{
header("Location: login.php");
die("Redirecting to login.php");
}
else if(!empty($_SESSION['admin'])) //if admin is not empty it goes to admin area
{
header("location: memberlist.php");
}
else if(!empty($_SESSION['user'])) //same here if user is present,then it leads to user area
{
header("Location: user.php");
}
Related
I assume this can simply be done with permissions, but I cannot seem to get it to work. I was trying to make the page check the user for a permission using the code below, otherwise it redirects to home. It always redirects though and I do not know why.
<?php
if(!isset($_SESSION))
{
session_start();
}
if ($_SESSION['permission'] == 0) {
header("Location: ./index.php");
exit;
} else {
if (!isset($_SESSION['authemail'])) {
header("Location: ./index.php");
exit;//Redirect to the index
}
Edit: I added a session dump and both the userID and permission are null. What am I missing from here as I cannot figure it out?
<?php
session_start();
include ('../config/config.php');
/* basic field validation */
$email = trim($_POST["email"]);
$password = trim ($_POST["password"]);
/* check if details are empty, redirect if they are */
if (empty($email) or empty($password)) {
$_SESSION["message"] = "You must enter your email and password";
//Redirect to index
header("Location: ../index.php");
exit;
}
/* sanitise the input */
$email = strip_tags($email);
$password = strip_tags($password);
/* SQL user selection query, with error handling for the SQL */
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($mysqli,$query) or exit("Error in query: $query. " . mysqli_error());
/* on query success, set sessions for email and userid */
if ($row = mysqli_fetch_assoc($result)) {
$_SESSION["authemail"] = $email;
$_SESSION["userid"] = $id;
$_SESSION["permission"] = $permission;
/* redirect the user to the secured page */
header("Location: ../loggedin.php");
} else {
/* display error if login was not successful and redirect to index */
$_SESSION["message"] = "Could not log in as $email - $query";
header("index.php");
}
?>
Try to set a flag in the database for someone who is an admin. Then on any specific page that only admins can access you should check this user variable.
if(!$user->isAdmin()){
header("Location: ./login.php");
exit;
}
If you do not have a $user object available, simply call a function that can query the database for the necessary variable.
if(!isUserAdmin()){
header("Location: ./login.php");
exit;
}
Also since both cases of yours redirect to index.php, you can combine the statements:
if($_SESSION['permission'] == 0 || !isset($_SESSION['authemail'])){
header("Location: ./index.php");
exit;
}
Make sure you are debugging to make sure the SESSION values are set/get as expected. Your code is redirecting because one of the conditions is true. Debug and find the bug.
I have been trying to display a specific error/warning message when a specific conditions is met. To be specific,
1) Unregistered or invalid user will get the $errMsg2 error message(I have this done)
2) Registered and 'notvoted' user will login successfully and proceed with the voting flow(I have this done)
3) Registed and 'voted' user should have something like "You have voted!" error message. Instead it kept on displaying the $errMsg2 error(Which is my main issue here).
*I have declared $stat and $stat2 respectively as it matches my mySQL db variables/structure.
I have tried playing around a lot with the if/else statement but I can't get the $stat2 conditions to meet.
Please help.
Below is my php code,
$stat='notvoted';
$stat2='voted';
//Create query
if($position=='Admin') {
$qry="SELECT * FROM admin WHERE username='$login' AND password='$password'";
}
if($position=='Student') {
$qry="SELECT * FROM students WHERE username='$login' AND password='$password' AND status='$stat'";
}
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
if($position=='Student') {
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['username'];
$_SESSION['SESS_COURSE'] = $member['course'];
$_SESSION['NAME'] = $member['name'];
session_write_close();
header("location: candidates_list.php");
exit();
}
if($position=='Admin') {
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
session_write_close();
header("location: admin/index.php");
exit();
}
}else if($stat2==TRUE){
header("location: index.php");
$_SESSION['errMsg3'] = "You have voted!";
exit();
}else{
header("location: index.php");
$_SESSION['errMsg2'] = "Invalid username or password, please re-
enter or register first";
exit();
}
}else {
die("Query failed");
}
You need to fetch the voting status from the database and compare it with 'voted'.
Here is some code you might be looking for:
//Create query
$qry = "SELECT * FROM students WHERE username='$login' AND password='$password'";
$result = mysql_query($qry);
//Check whether the query was successful or not
$result or die("Query failed");
// Check for wrong credentials
if (mysql_num_rows($result) == 0) {
header("location: index.php");
$_SESSION['errMsg2'] = "Invalid username or password, please
re-enter or register first";
exit();
}
// Login successful, fetch properties
$member = mysql_fetch_assoc($result);
if ($position == 'Student') {
// Check voting status
if ($member['status'] == 'voted') {
header("location: index.php");
$_SESSION['errMsg3'] = "You have voted!";
exit();
}
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $member['username'];
$_SESSION['SESS_COURSE'] = $member['course'];
$_SESSION['NAME'] = $member['name'];
session_write_close();
header("location: candidates_list.php");
exit();
}
if ($position == 'Admin') {
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
session_write_close();
header("location: admin/index.php");
exit();
}
There are however several issues remaining:
It is not clear how $position got it's value. Ideally the students table should
have this information (or a reference to it), and you should check that the connecting
user is not trying to take the administrator role without having the right to do so.
It is not enough to have some limitations on the client (HTML) side, for making
sure this does not happen. You must check again in the database that it is OK for
the user to act as administrator.
$login and $password should first be checked not to contain anything that would
turn the SELECT statement into something revealing unwanted information or
having side-effects (read about SQL injection ). One important
improvement would be to not allow the presence of a single quote in
either $login or $password.
The code uses deprecated mysql_ functions. Instead, the MySQLi or PDO_MySQL
extension should be used.
Less important: it is strange to see $_SESSION['SESS_MEMBER_ID'] being set
with a different field's value depending on the position. It seems more logical to build your
code in such a way that it always corresponds to same field: either username
or id, the session variable name suggesting it should be the second.
I am trying to code a simple script,
I created a " ADMIN Panel " , so if the user is admin (admin=1) then he can pass and see the link/file
If he is not (admin=0) then he should be redirected to login page , and if is not Session['username'] he should go back to login page ,
but it seems that i have a problem with this code, in user panel it works , but in admin panel it doesn't
<?php
include './includes/db.php';
session_start();
// ADMIN CHECk
$username = mysql_real_escape_string($_SESSION['username']);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND admin=1");
$count = mysql_num_rows($result);
if($count != 1) // make sure user is a admin
{
session_start();
session_destroy();
header("location: login.php");
die;
}
if(isset($_GET['act']))
{
if($_GET['act'] == "logout")
{
session_start();
session_destroy();
header("location: login.php");
}
}
?>
Ok, first thing i see is that you don't declare the session first. Secondly, the mysql function is deprecated, mysqli will do what you need done. This fix should work for you. Also it would be easier to have a logout.php.
db.php
<?php
$db = new mysqli(host, user, pass, database);
?>
Then, in your page, you can run the queries like so:
<?php
session_start();
include './includes/db.php';
//check that the session exists
if(!isset($_SESSION['username'])
{
//the session does not exist, redirect
header("location: login.php");
}
// ADMIN CHECk
$username = $db->real_escape_string($_SESSION['username']);
$result = $db->query("SELECT * FROM users WHERE username='$username' AND admin='1'");
$count = $result->num_rows;
if($count != 1) // make sure user is a admin
{
header("location: login.php");
}
?>
Then in logout.php, you should remember to actually unset the session variables
<?php
session_start();
//unset session variables
unset($_SESSION['username']);
session_destroy();
header("location: login.php");
?>
I am new to php and I am making a basic login script.
All I want to do is log in and have the cookie for my user_id stored.
It works on all of my other pages, except my index page which is one directory up.
So on my index page, I have this if statement:
<?php
if (!isset($_COOKIE['user_id'])) {
sign_in();
} else {
echo "You're already logged in!";
}
?>
No matter what I do, the sign_(); function always shows.
But here's the kicker:
On my login script, the whole thing goes through as if I successfully logged in.
I send it back to this page using:
header("Location: ../index.php");
(It is up one directory)
However, when I make it link to a page in the same directory, it registers the cookie and everything is alright.
header("Location: show_user.php");
If you want a hands on view, you can go to http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/signup.php to make your account. And http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/show_user.php to view it. And notice how the index page doesn't register the cookie.
How I tried to set the cookie:
if (isset($_POST['usernamelogin'])) {
$user_login = $_REQUEST['usernamelogin'];
$pass_login = $_REQUEST['passwordlogin'];
$pass_login = trim(crypt($pass_login, $user_login));
$login_query = sprintf("SELECT username, user_id FROM user WHERE username = '%s' and password = '%s';", mysql_real_escape_string($user_login), mysql_real_escape_string($pass_login));
$loginresult = mysql_query($login_query, $dbConn);
echo $login_query;
if (mysql_num_rows($loginresult) == 1) {
$userinfo = mysql_fetch_array($loginresult);
$username = $userinfo['username'];
$userid = $userinfo['user_id'];
setcookie('username', $username);
setcookie('user_id', $userid);
header("Location: show_user.php");
exit();
} else {
echo "Couldn't find your account!";
}
}
Please excuse my unrefined page and amateur mistakes. I have a lot to learn.
Any ideas?
Thank you for your time.
Check if you have the cookie with the following
<?php
var_dump($_COOKIE);
//if (!isset($_COOKIE['user_id']))
if (empty($_COOKIE['user_id']))
{
sign_in();
}
else {
echo "You're already logged in!";
}
?>
I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.