Creating an admin only page in php - php

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.

Related

PHP link to page.php from another file

Im creating my first page in PHP with login form.
Here is my question,
I have this kind of structure:
MAINFILE:
-index.php
-asstes(file)
-config(file)
-includes(file) (with header.php)
-user(file) with user.php
and after loggin from index.php i want to direct user to user.php but after using header("Location: user/user.php"); i get ERROR 404.
Does anybody knows how to redirect to page in another file?
Thanks!
<?php
$error = "Email or password was incorrect<br>";
if(isset($_POST['login_button'])) {
$login = $_POST['log_login']; //sanitize email
$_SESSION['username'] = $login; //Store email into session variable
$password = md5($_POST['log_password']); //Get password
$check_database_query = mysqli_query($con, "SELECT * FROM users WHERE login='$login' AND password='$password'");
$check_login_query = mysqli_num_rows($check_database_query);
if($check_login_query == 1) {
$row = mysqli_fetch_array($check_database_query);
$username = $row['login'];
$role =$row['role'];
$_SESSION['username'] = $username;
if(role == "admin"){
header("Location: admin.php");
$_SESSION['role'] = true;
}
else {
header("Location: /user/user.php");
$_SESSION['role'] = false;
}
exit(0);
}
else {
echo $error;
}
$_SESSION['log_login'] = "";
$_SESSION['log_password'] = "";
}
Actually if in your index.php you have a login form which sends a POST request then, after a successful sign-in you can redirect user using:
header('Location: /user.php');
exit(0);
Path passed in location is relative to user's current position so if your file user.php is in the root folder then use /user.php; if in user so that the filename is user/user.php then use:
header('Location: /user/user.php');
exit(0);
Yet a lot of that may be caused by the way you actually sign in your user and how you manage the session creation so would be great and helpful if you have shared the code.

Restricting access to an admin page through sessions

I've been stuck trying to block access to an admin page using PHP. The PHP is below but I can't figure out which combination of statement I need to use for the permission to be selected.
When I dump my session it's always null but the email session is there. It's a simple login requiring email and password. I basically want it to also get their permission from the DB.
<?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 email, permission 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["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");
}
?>
Feel free to edit some of the text out if it isn't relavent.

Displaying error message for specific conditions

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.

Checking if user is admin or normal

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");
}

Redirecting to another page, using variables from the first one

I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();

Categories