Show text only for specific user in php - php

I am trying out simple PHP page. I am trying out the following:
<?php
include("db/db_config.php");
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql = mysqli_query($bd, "SELECT username FROM cmn_users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username']; //get session username
echo ("<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'><a href='/admin.php'>ADMIN</a> | <a href='/logout.php'>Logout</a></h1></span></p>");
?>
I want to show admin page (link) only for a particular user. Like admin should be hidden near loggout if admin user doesn't login...How do I do it?
I have got session's userID but I don't know how control the text in php/html.
Help on this will be great.
Thanks!

If session userId is this then show admin
The semantics of your statement are your exact code:
if ($_SESSION['username'] == 'admin') {
// output the admin stuff
}
(Or however you check if the user is an admin. Based on username, some identifier, something else, etc. Your question doesn't specify.)
So you'd output whatever is before the admin link, then conditionally output the admin link, then output whatever is after it. Something like this:
echo "<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'>";
if ($_SESSION['username'] == 'admin') {
echo "<a href='/admin.php'>ADMIN</a> | ";
}
echo "<a href='/logout.php'>Logout</a></h1></span></p>";
There are many other ways you can structure it as well. Perhaps store the resulting links in variables and conditionally concatenate them as needed, then echo the result of that only once at the end.
But the concept is the same however you do it. If the user is an admin, output the admin link. That way if the user is not an admin, they never see that link.
Note: The admin page itself must also implement security. There is nothing to stop a user from guessing the link and trying to open that page. Do not consider the approach in your question to be security. This is nothing more than user experience.

you need to store html links in your variables, and use them where needed, like this,
<?php
include("db/db_config.php");
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql = mysqli_query($bd, "SELECT username FROM cmn_users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username']; //get session username
$adminLink = " <a href='/admin.php'>ADMIN</a> | ";
$logoutLink = " <a href='/logout.php'>Logout</a>";
?>
// suppose your html header link container
<div>
<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'><?php echo $adminLink.$logoutLink ?>
</h1></span></p>
</div>
============================================
for blocking acces on admin page
<?php
// start session
session_start();
// check if username is admin
replace it with your admin user name
$adminUsername = "admin";
if($_SESSION['login_user'] !== $adminUsername){
// isn't admin, redirect them to a different page
header("Location: /someotherpage.php");
}
?>

Related

Not able to create proper session's for User management application in php

I have created a user management application in PHP, Where Super Admin has a rights/permissions to grant and revoke permissions to the Users.
I have created Session for all the users including the Super Admin.
Below code for the same:
$_SESSION['User_login'] = $single_value['user_name'];//USER NAME
$_SESSION['permission'] = $single_value['permission']; // Granted permissions
$_SESSION['role_code'] = $single_value['role_id'];// ROLE CODE
The working is fine but I'm facing the problem in the below condition.
Super Admin has a right to create users with Create_user.php file and USER Test has a right to access the only download_file.php
When User Test Logins to the download_file.php file he is able to do all the tasks mentioned in that file but if Test user enters the Create_user.php in URL then he is able to view that file which belongs to Super Admin without any problem.
So I'm confused here how to stop this process when 1 user does not have the rights/permissions to open a particular file, the user should be directed to the home page or any error something.
You'll need some kind of conditional check at the beginning of your Create_user.php file which check what permissions the user requesting that page has. Something like this:
if ($_SESSION['permission'] != 'Admin') { // or however you name your permissions
header('Location: /download_file.php'); // redirect non-admin users
}
// ... admin stuff follows
This can be achieved with the help of in_array() function.
Creating a sperate table for all the menu with the page name and checking the currently rendered page with the given/granted permissions to the logged in user.
menu table:
Below code for checking the permissions.
CHECK.PHP
function check($filename)
{
include_once('config.php');
$sql = "SELECT name from menu where page_name = '".$filename."' ";
#echo $sql;
$result = $conn->query($sql);
if($result->num_rows > 0 )
{
while($row = $result->fetch_assoc())
{
if(!in_array($row['name'],explode(",",$_SESSION['permission'])))
{
header('location:logout.php');
}
#echo "data = ".$row['name']; echo "<br> My permission = ".$_SESSION['permission'];
}//EOF WHILE
}//EOF IF
else
{
echo "0 result";
}
}//EOF CHECK();
calling this function where you want to check permissions
Create_user.php
<?php include_once 'check.php';
check(basename($_SERVER['PHP_SELF'])); #passing the name of current file.
?>
<!DOCTYPE html>
<!-- Rest of the code -->
<html>

$_SESSION not working/ sending out wrong result in php

I am trying to navigate to a different page whenever a user clicks on a particular link [basically these are user links which navigate to user profile page when clicked].
My problem if I store the SESSION variable and display it in the same page as the link, it echos out all the emails ids corresponding to that user, but as soon as I navigate to a different page,I can see SESSION displays the wrong result [some other email id].
Here is my code.
<?php echo $firstName.' '.$lastName;?>
This link is displayed as many times as there are records in the database.
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
$_SESSION['email'] = $email;
echo $_SESSION['email'];
header('location: home.php');
}
?>
Now if I just echo the email like above on this page itself, it displays all the emails corresponding to that user. Like this.
user1 : emailid1
user2 : emailid2
But as soon as I navigate to home.php, the SESSION variable always prints out the first email only.
home.php
session_start();
echo 'email id is '.$_SESSION['email'];
I know I am going wrong somewhere but any suggestions would be of great help.
Try with below code.
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
session_start();
$_SESSION['email'] = $email;
echo $_SESSION['email'];
header('location: home.php');
}
?>

Making a certain log in pattern go to another page location

I am constructing a social networking site. Users who register and log in correctly are redirected to home.php with a $_SESSION made accordingly.
But I have manually made an admin user with the username of freddy (the username is required to log in). What I am trying to state is that "if the username is equal to freddy, then take him to admin_home.php".
What I have tried is to create two separate $_SESSION's.
$_SESSION created for normal user:
// if the user credentials are correct, log the user in:
$_SESSION["user_login"] = $user_login;
header( "Location: home.php" ); // refresh page
exit;
}
$_SESSION created for admin:
if ($account_type == "admin"){
// Create seperate session for admin
$_SESSION["user_login"] = $admin_login;
header( "Location: admin_home.php" ); // refresh page
exit;
}
Full query:
<?php
$user_query = mysqli_query ($connect, "SELECT * FROM users WHERE username = '$user_login' AND password = '$decrypted_password' AND closed='no' LIMIT 1");
$check_for_user = mysqli_num_rows ($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_for_user==1){
while ($row = mysqli_fetch_array($user_query)){
$user_id = $row['id'];
$account_type = $row['account_type'];
}
// if the user credentials are correct, log the user in:
$_SESSION["user_login"] = $user_login;
header( "Location: home.php" ); // refresh page
exit;
}
if ($account_type == "admin"){
// Create seperate session for admin
$_SESSION["user_login"] = $admin_login;
header( "Location: admin_home.php" ); // refresh page
exit;
}
else {
// if user row does not equal 1 ...
echo "<div class='wrong_login'>
<p> Username or password is incorrect, please try again. </p>
</div>";
exit();
}
}
?>
With the current code, logging in with the username freddy - which should take me to admin_home.php, takes me to home.php which is not what I want.
First a quick suggestion. You should not store plain-text passwords if you want your users to trust you. See this doc about hashing passwords, especially the part about salting your hashes.
I would say best practice would be to create a user class, matching your database table, and create an instance of it when the user logs in, and store that class instance in your session variable. Currently you don't store things like user ID, or account type, which you'll probably want to use later.
The problem with your code as it is written, as #FirstOne points out, is that you are exiting as soon as the user is logged in correctly, instead of checking their account type first.

How to store user id session from login page in php

i am creating login page where user will be redirected to his/her profile page. Profile page contains the articles of that user...
I have problem in login page, actually i want to store user id in
session from login page.. as i am storing user_email in session and it
does successfuly.. but it gives error on user_id session (undefined
index)....
addition
i want to show articles of logged in user through user_id session...
Here is the code of login page..
<?php
if(isset($_POST['login'])){
$user_email=mysqli_real_escape_string($con,$_POST['user_email']);
$user_password=mysqli_real_escape_string($con,$_POST['user_password']);
$encrypt= md5($user_password);
$check_login="select * from users where customer_email='$user_email'
AND customer_pass='$user_password'";
$run_login= mysqli_query($con, $check_login);
$row = mysqli_fetch_array($run_login);
$num = mysqli_num_rows($run_login);
$user_id=['customer_id'];
if($num==1){
$_SESSION['customer_email']="$user_email";
$_SESSION['customer_id']="$user_id";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "This Username Doesnt Exists or Empty Login !";
}
}
?>
</div>
Step 1:
Do not forget to put session_start();
Step 2:
Change $user_id=['customer_id']; to $user_id=$row['customer_id'];
You must set $user_id only if there is a return from DB (otherwize you don't know this id)
if($num==1){
$user_id=$row['customer_id'];
// ....
}

PHP - session multi user and admin privileges

Can anyone help me?
Im still newbie in using most of the php stuff here. I kinda having a problem with creating multi users using session.
What I want to do is this. An account exclusive only of admin and an account only for normal users.
Admin privileges will be able to access pages for admins only while normal users who logs in, will be able to access pages meant for users only.
So far Ive created a single user login credentials. Which is for admins only. Im really confused how do I add non-admin in order to access pages only for them.
Can anyone help me with this code?
This is the home page
<?php
//Initialize Session
session_start();
error_reporting(E_ALL ^ E_NOTICE);
//$name = $_SESSION['username'];
if(isset($_SESSION['username']))
{
header('Location: index_admin.php');
}
?>
This is the admin page
<?php
// Inialize session
session_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['username']))
{
header('Location: index.php');
}
?>
This is the login form
<form action="login.php" method="post">
<input type="text" name="uname" placeholder="USERNAME . . . " autofocus/>
<br/>
<input type="password" name="pword" placeholder="PASSWORD . . . " />
<br/>
<center><input type="submit" name="submit" value="LOGIN" /><button type="reset" value="Reset" />RESET</button></center>
</form>
This is the login.php
<?php
session_start();
include("config.php");
$login = mysql_query("SELECT * FROM users WHERE (username = '" . mysql_real_escape_string($_POST['uname']) . "') and (password = '" . mysql_real_escape_string($_POST['pword']) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1)
{
// Set username session variable
$_SESSION['username'] = $_POST['uname'];
// Jump to secured page
header('Location: index_admin.php');
}
else
{
// Jump to login page
header('Location: index.php');
}
?>
This is the database
user_tbl
id = 1
username = admin
password = 12345
Thanks in advance for the assitance.
It seems from your question that you'll use the same login page for both administrative users and non-administrative users. That's the case for which I'll offer an answer.
In the process of validating a particular user's name and password, you need to determine what privilege level that user has been granted. You might have a column called "privilege" in your user table.
usr_tbl needs to look something like this:
id username password privilege
1 admin W$^%^$%^%^% admin
2 reggel DJDT&646364 user
3 ollie DTHDHFGEERT user
Upon login, you'l read the usr_table and pull that user's value out of the column and store it as a session variable something like this:
$_SESSION['privilege'] = $privilege; /* from user table */
Then you can do logic like this to decide what your user should see, and what she should be able to do.
if ( 'admin' == $_SESSION['privilege'] ) {
// Jump to secured page
header('Location: index_admin.php');
}
else {
// Jump to login page
header('Location: index.php');
}
In later page views, if your session logic is functioning correctly, the $_SESSION['privilege'] variable should continue to be available.
p.s. mysql_ APIs for security code? Really?
You need to add a new field in your database for user type (admin/normal_user).
In your login script save the user type in session (admin/normal_user).
Now on every top of page check the session value of user type if it is admin let the page open and if it is normal_user redirect page to login.
ideally you need to expand on the data structure serving this code: Set up a table of users and a table of groups; the groups will imply access rights. When you submit the login page, check the database for the username, then:-
1) If no match, return to "access denied" screen
2) if match, xref with groups table to determine privilege level of this user. Then:-
2a) if admin, return to admin screen, setting appropriate session vars to store that decision.
2b) Else, return to normal user screen, ditto setting appropriate session vars.
Your core problem is that upon entering "the" homepage, you are simply checking if the username is set, and then taking the user to the admin screen. This is wrong. Try to split out your logic into smaller simpler steps, and consider the "if-else" logic in human terms. "What do I want to happen?" then "What do I need to know to ascertain how to do that?".
Good luck!
I use the same but I got one error
This page does not work local host has redirected you too often.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
<?php
// Include config file
require_once "config.php";
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$_SESSION['privilege'] = $privilege; /* from user table */
if ( 'admin' == $_SESSION['privilege'] ) {
// Jump to secured page
header('Location: index_admin.php');
}
else {
// Jump to login page
header('Location: index.php');
}
?>
<?php include "theme/header.tpl"; ?>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
Reset Your Password
Sign Out of Your Account
Users
</p>
<?php include "theme/footer.tpl"; ?>

Categories