i'm trying to add roles for certain pages on a small internal site i am running.
i assign the following sessions when user logs into the site login form;
// Register $username, $role Sessions and redirect
$_SESSION['username']= $username;
$_SESSION['accessLevel'] = $role;
$_SESSION['is_logged_in'] = true;
i then have the following on my logout.php page;
<?php
session_start();
session_destroy();
header("Location: ../login.php");
?>
i want to restrict page based on the users $_SESSION['accessLevel']
for instance only show page if $_SESSION['accessLevel'] == 'admin' else redirect to login page (or error page)
here is what i have on an admin page;
<?php
session_start();
if (!isset($_SESSION['username']) && $_SESSION['accessLevel'] == 'admin'){
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<p>ADMIN AREA!! </p>
<p>username: <?php echo $_SESSION['username'];?></p>
<p>Access: <?php echo $_SESSION['accessLevel'];?></p>
</body>
</html>
<?php
}
else {
header("location:../login.php");
}
?>
now the page redirects to login.php when i login using admin credentials if i remove the check i print_r the sessions are correct;
$_SESSION['accessLevel'] = admin
$_SESSION['username'] = testuser
where am i going wrong?
You want the username to exist, right now you are checking to see if it is not isset(). Update your conditional to:
if(isset($_SESSION['username']) && $_SESSION['accessLevel'] == 'admin') {
// HTML here
} else {
header("location:../login.php");
}
Also, a side note: if you ever have an edge case were you set a username value but not a accessLevel value, you will get a fatal error with this conditional. You should be making sure that the accessLevel is set to be safe:
isset($_SESSION['username'], $_SESSION['accessLevel']) && $_SESSION['accessLevel'] == 'admin'
Related
Problem
I am building a panel for an admin for a web system. I have to make sure that hackers, if they have knowledge of the names of the files on this server cannot access certain pages directly without at least logging in.
Now after looking at similar php code used to achieve this, i discovered that after you have verified the existence of the user from the database, you start a session and then you store a boolean variable indicating whether this user is logged in side the $_SESSION["loggedin"] as true.
I did exactly that in my login.php file, and also included a conditional structure to check if user is logged in on top of my admin_upload.php file. It checks the value of $_SESSION["loggedin"].
What I Expected
I expected that whenever i enter the url to access diirectly the admin_upload.php file on the server without logging in, it would take me to login.php to start a session before i can view that page, instead it opens the page with values that am supposed to grab from login with session null.
Code
The login.php file is posted below
<?php
$conn=mysqli_connect("localhost","root","","rating");
if(!$conn){
echo "Connection to database was unsuccesful";
}
$username="";
$password="";
$username=trim($_GET["p"]);
$password=trim($_GET["q"]);
//echo $password;
$sql="SELECT username from Admin where username="."'".$username."'";
//echo $sql;
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){
$pass="SELECT Password FROM Admin WHERE username="."'".$username."'";
$real_qry=mysqli_query($conn,$pass);
if(mysqli_num_rows($real_qry)>0){
$row=mysqli_fetch_row($real_qry);
$pass=$row[0];
//echo $password;
if(password_verify($password, $pass)){
//start session
session_start();
//store the admn name in a session
$_SESSION["username"]=$username;
$_SESSION["loggedin"]=true;
echo "password verification passed";
}else{
echo "Incorrect password";
}
}
}else{
echo "No account with that username was found";
}
?>
The admin_upload.php is posted below
<?php
session_start();
//initiaize the session
//check if the user is logged in
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] !== true){
//redirect to welcome.php if false
header("location: login.php");
exit;
}
//session_start();
$name=$_SESSION["username"];
//if he is loged in then display images to be added
include "layout/product_add.php";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="materialize/css/materialize.min.css"/>
</head>
<body>
</html>
Any help to make this check if user is logged in and redirect accordingly is greatly appreciated, Thank You.
Your going to want to update
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] !== true){
with
if(!isset($_SESSION["loggedin"]) || !$_SESSION["loggedin"]) {
That verifies that the $_SESSION["loggedin"] is not set OR that its set and NOT TRUE then it will do your redirection
I have a login system and when the users login, they are sent to a new file called user.php. In the login file, I have this code:
$user = $check->fetch_assoc();
if (password_verify($_POST['password'], $user['password'])) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
and when the user successfully logs in, he is sent to the user.php file and the code in the the file looks like:
<?php
// Start The session
session_start();
// Chaeck if the user is logged in.
if ($_SESSION['logged_in'] = false) {
$_SESSION['message'] = 'You must Login to continue use this section.';
header('location: error.php');
} else {
$username = $_SESSION['username'];
echo $username;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<h1>
Welcome, <?php echo $username?>,
</h1>
</body>
</html>
But when the user logs in he gets the undefined index: username. I want to know why if I am using Sessions.
$user = $check->fetch_assoc();
if(!empty($user)) {
$passwordCheck = password_verify($_POST['password'], $user['password'])
if ($passwordCheck) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
}
Here is modified welcome page
<?php
// Start The session
session_start();
// Chaeck if the user is logged in.
if (!isset($_SESSION['logged_in']) && $_SESSION['logged_in']=="") {
$_SESSION['message'] = 'You must Login to continue use this section.';
header('location: error.php');
} else {
$username = $_SESSION['username'];
echo $username;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<h1>
Welcome, <?php echo $username?>,
</h1>
</body>
</html>
Please next time try to send a full code so that helping you will become a lot easier. Username is undefined probably because you did not initialize session session_start(); in your authentication script eg login.php that first handle the session. Again u will need to mitigate session fixation attack by generating new session for each login user session_regenerate_id();
$user = $check->fetch_assoc();
if (password_verify($_POST['password'], $user['password'])) {
// initialize session
session_start();
// prevent session fixation attack
session_regenerate_id();
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
Optionally
At user.php
Remove the way your are performing session check and replace the code below.
you can check if users session is set using this simple script
<?php
// initialize session if session has not be initialize otherwise remove it
session_start();
if(!isset($_SESSION['username']) || (trim($_SESSION['username']) == '')) {
echo "you must login";
exit();
}else{
// login flows
}
?>
Pls send full code if this does not solve your problem
Good morning/evening,
I'm stuck and I need some help in PHP.
I am trying to code up an admin dashboard. And I want to check if user is logged in, if not , redirect to the login page.
My index.php is this:
<?php
$pagename ="Index";
#require_once('inc/head.php');
?>
<body>
CONGRATS! Welcome to the Admin dashboard.
</body>
</html>
My login page:
<?php
$pagename = "login";
$adminUser = "admin";
$adminPass = "admin";
#require_once('inc/head.php');
// If POST is submitted and IDs match the ones set
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST["username"] == $adminUser && $_POST["password"] == $adminPass)
{
session_start();
$_SESSION["username"] = $adminUser;
$_SESSION["login"] = true;
echo '<script>alert("Congrats, you logged in");
window.location = "index.php"; </script>';
/* I skip the line underneath because for unknown reasons my code
Doesn't fully run through. So I redirected with the JS above instead.
header("Location: index.php");
exit(); */
}else{
echo '<script>alert("Incorrect username or password!'");</script>';
}
}
?>
<html>
<!-- login page here -->
</html>
And here goes my head.php:
<?php
// If we AREN'T on the login page , check if session exist. If not send to login
if($pagename != "login")
{ if(!$_SESSION['login'])
{
header('location: login.php');
exit();
}
}
?>
There is alot of things wrong with this and I know but as of now I'm trying to fix my login in issue. Whenever I log in I get the JS pop up that says I successfully logged in, but I don't get redirected to the index. I think I do get sent to my index.php ( there's no reason for my JS redirect to NOT function ) but my index sends me right back to login and I don't understand why.
Start Session in head.php page.
head.php
<?php
if($pagename != "login") {
session_start();
if(!$_SESSION['login']) {
header('location: login.php');
exit();
}
}
?>
I have created a login script and it works fine, however, I would like to implement sessions.. I am currently having some trouble with it because my session script is only partially executed. Below is my login script and the test page I'd like it to redirect to, IF the user is logged in.. I want it to display the test page, if not, then I want it to redirect back to the login page (or in this case, the index.php file) and ask the user to login... see code below:
loginconfig.php:
<?php
// Create a connection
include("dbconfig.php");
if (isset($_POST['submit'])) {
if (empty($_POST['username']) or empty($_POST['password'])) {
header("location:index.php?msg0=Please complete the required fields.");
}
elseif (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = mysqli_query($conn, "SELECT * FROM logininformation WHERE username = '$username' and password = '$password'") or die(mysqli_error($conn));
$login = ($sql) ? mysqli_fetch_assoc($sql) : false;
if (($login) == 0) {
header("location:index.php?msg1=Invalid username or password, please try again.");
}
elseif (($login) > 0) {
session_start();
$_SESSION['login'] = $_POST['username'];
//header("location:index.php?bid=$username&msg2=You are unable to log in at this time. Website is under construction.");
header("location:test.php?bid=$sessionwork");
}
}
}
?>
test.php:
<?php
session_start();
include("dbconfig.php");
$username = $_GET['bid'];
var_dump($_SESSION['login'];
// If user is logged in:
if(!empty($_SESSION['login'])){
echo "Welcome $username";
}
// If user is not logged in:
elseif(!isset($_SESSION['login'])){
header("location:index.php?msg4=You need to be logged in!");
}
?>
<html>
<head>
<title> user page </title>
</head>
<body>
<form name="logout" method="post" action="logout.php">
<input type="submit" name="logout" value="logout">
</form>
</body>
</html>
logout.php
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
Now if you look at the test.php file.. I have sort of told it to check if a user is logged in. But unfortunately, the script only manages to execute the script where it says if the user is not logged in.. redirect to index.php... even if the user enters the correct login credentials and actually logs in. What could be the issue?
Any help will be much appreciated.
It should be like this in test.php:
if(isset($_SESSION['login'])){
echo "Welcome $_SESSION['login']";
}
else{
header("location:index.php?msg4=You need to be logged in!");
}
The same error is repeated in loginconfig.php.
Initially, I did not have a logout.php file.. therefore I was making the mistake of not destroying my session. The change I had to make to my initial scripting was to create a logout.php file. But when I did, the problem was still present.. in order for it to work.. I made the following changes to the logout.php file.. see below:
BEFORE:
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
AFTER:
<?php
session_start();
session_destroy();
header("location:index.php");
exit();
?>
Thank you for those who helped, especially #Epodax for the GREAT support.
Successful login on my login page should direct to a homepage (which it does - I double checked to see is the variables are set and they are when a correct username/password is entered). Otherwise, the login page should be private.
LOGIN PHP (works fine)
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$error_message= "";
$user_name = "";
$user_password= "";
$_SESSION['username']="";
$_SESSION['employeeNumber']="";
if (isset($_POST['submit'])) {
$user_name = $_POST['user'];
$user_password= $_POST['pass'];
// ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
if(!empty($user_name) && !empty($user_password)) {
$query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";
$result = mysqli_query($dbc, $query)
or die ('Error querying username/password request');
if(mysqli_num_rows($result) == 1) {
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['username'];
$_SESSION['employeeNumber'] = $row['employeeNumber'];
}
header("Location: /LESSON5/3%20-%20HOMEPAGE%20:%20WELCOME.php");
exit;
} // end if rows
else {
$error_message = "You were not able to log in";
} // end else
// Direct to other webpage
} // end query
} // end isset
?>
The homepage should only be visible if the $_SESSION variables are set. If the user is not logged in (session variables not set) then the homepage should redirect to the login page. Now, I added a validation to see if variables are not set (!isset). This validation keeps the page from showing any content. When I delete this validation the HTML shows up fine. When I delete the validation and echo the variable values I get the values returned.
It's just the if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) keeping from showing any content on the page.
HOMEPAGE
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) {
header("Location: /LESSON5/1%20-%20LOGIN.php");
}
?>
<!DOCTYPE html>
<head>
<title></title>
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="/LESSON5/5_Signup_CSS.css">
</head>
<body>
<p><span id="logout">Logout</span></p>
<hr>
<h1>Welcome to my homepage! <br> You have successfully logged in.</h1>
<?php
mysqli_close($dbc);
?>
</body>
</html>
Is there any reason why that validation is keeping the PHP from showing the HTML(if user login is correct) or redirect the page(if user not logged in)?
Basically error is in your php if condition. One parenthesis is missing. change like this:-
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']))
Note:- try to add error_reporing at the top of your all php pages so that you can get php errors if happen. check the manual of error_reporing on php site. Thanks.
If you are working on local server you can change your php.ini settings for this.
You can get how to change php.ini setting on google easily.
ini_set is function of php is for this purpose if you want to do it programmatically not with php.ini directly.