I'm new to PHP. I have created a system where the users include user and admin. I login as a user in the system and the URL is localhost/View/user.php.
When I change the URL from localhost/View/user.php to localhost/Admin/admin.php, the user automatically has an admin interface.
My question is - how can I stop the user from being able to change the URL to /admin.php and accessing the admin interface?
Here are some examples:
http://php.net/manual/en/features.http-auth.php
But just know that this is not something you should use for a real website, unless you know all the security issues and how to solve them.
But for learning something about php and playing around this could be a place to start :)
Well you can't force a user to not modify the url in his browser.
What I think you are looking for is some kind of user roles.
So when you already have a login system I assume you store the username and password somewhere (mostly a database).
What you can do now is to add an additional field "roles" and write in "user", "admin" or something to differentiate users.
At your admin-page you could than check if the user has the role "admin", if not you can redirect the user to some other page (e.g. index) or just print out "Access denied"
(There are also a lot of tutorials about login systems and user roles for php out there. I would recommend to take a look at that also)
Simple add flag for user and check weather the flag is set or not if not than through user to error page.
Example
for admin $flag_admin=1;
and store this in session and check if flag is set than allow him to access admin screen else show error page.
A simple answer is that you should store the fact that the user has logged in via $_SESSION (such as $_SESSION['user_id'] = [something from the database]) and that can be tested later (such as isset($_SESSION['user_id']) followed up by looking that user up again in the database to make sure they do actually have admin rights. If they don't you can simply redirect them back to the login page via header('Location: http://whereever.com/login.php') or what-not. This isn't foolproof security, but it's a start.
If the session isn't automatically initialized (unlikely but possible depending on server configurations), you can start it at the beginning of each of your scripts with session_start().
To be more specific. Let's say that you have a script called user.php that takes in user login information. In that you might have something that looks like this...
<?php
session_start();
$login = (isset($_POST['login'])) ? trim($_POST['login']) : '';
$pass = (isset($_POST['pass'])) ? $_POST['pass'] : '';
if ($login !== '') {
$user = [db->lookup_somehow(where=>login is $login)]
if ([the hash of $pass is the same as the hash of the pass in $user]) {
$_SESSION['user_id'] = $user['user_id'];
header('Location: http://wherever.com/admin.php');
} else {
// say "invalid login"
}
} else {
// handle missing input
}
?>
And admin.php might look like...
<?php
session_start();
$user_id = (isset($_SESSION['user_id'])) ? $_SESSION['user_id'] : null;
$user = null;
if ($user_id) {
$user = [look up user from database based on their id];
if (!$user[has credentials to be an admin])
$user = null;
}
if (!$user) {
header('Location: http://wherever.com/user.php');
}
// else do admin stuff
?>
One possible solution to the problem is to check for admin permissions when the user navigates to the admin.php. If the user has adequate permissions, then the admin interface is visible. If the user does not have admin permissions, then they should be redirected back to user.php.
However, the better option would be to have a single login page - login.php. After logging in, the user permissions are checked, and the admin interface is made visible if applicable.
I have the proper solution.
suppose your admin's users id is 'admin' and your other users have other user id.
Then use $_SESSION('login_user') to login.
In your amdin page you want to protect from user you sholud put a condition that
$result = mysql_query("select username from adminlogin where username = '".$_SESSION['login_user']."'");
$result_value = mysql_fetch_array($result);
echo $result_value['username'];
if($result_value['username']!="admin")
{
header("Location: index.php");
}
Now it will check for user id = admin then it allow to access other wise it redirect the page to index.php that is our login page. If you can not understand then you can replay. Thanku
Related
I have a page for users named game.php, where they can update their profile etc. So when the admin logs in, they can still access game.php but I do not want them to do so. How do I prevent it?
I have 2 different log in page, 1 for normal users (logreg.php), 1 for admin (admin.php)
This is my game.php codes, where they restrict all users so I even if I am a normal user, it redirects me back to logreg.php, when I am supposed to be able to access it.
The status of the user will be "gamer" - a normal user OR
"admin" - for admin log in.
<?php
session_start();
ob_start();
If (!isset($_SESSION["username"]['status'])){
$_SESSION['username'] = $username;
$_SESSION['status'] = 'admin';
header("Location:logreg.php");
}
else {
$username = $_SESSION['username'];
}
?
Thanks in advance!!!!
In your if, you are checking the value of $_SESSION["username"]['status'] but in your code you are setting $_SESSION["username"] and $_SESSION['status']. You probably meant the if to read:
if (!isset($_SESSION["username"], $_SESSION['status'])) {
to check that both $_SESSION variables were set.
<?php
session_start();
ob_start();
If (isset($_SESSION["username"]['status'] && isset($_SESSION["username"]['status']=="admin")){
header("Location:logreg.php");
}
?>
try this code :)
I have a page for users named game.php, where they can update their profile etc. So when the admin logs in, they can still access game.php but I do not want them to do so. How do I prevent it?
I have 2 different log in page, 1 for normal users (logreg.php), 1 for admin (admin.php)
This is my game.php codes, where they restricts the admin from accessing and it redirects me back to logreg.php.
The status of the user will be "gamer" - a normal user OR "admin" - for admin log in.
<?php
session_start();
ob_start();
if (!isset($_SESSION["username"], $_SESSION['status'])) {
$_SESSION['username'] = $username;
$_SESSION['status'] = 'admin';
header("Location:logreg.php");
}
else {
$username = $_SESSION['username'];
}
?>
But here's the issue: how do I check if the user is logged in as admin at the admin.php (admin login page) and redirect them to the admin site instead of logging in again, while also making sure that the "gamers" can't access the admin site? It states that my site has redirected me too many times.
Here are my codes for admin.php
<?php
session_start();
ob_start();
if (!isset($_SESSION["username"], $_SESSION['status'])) {
$_SESSION['username'] = $username;
$_SESSION['status'] = 'gamer';
header("Location:admin.php");
}
else {
$username = $_SESSION['username'];
$_SESSION['status'] = 'admin';
header("Location:adminpage.php");
}
?>
Thanks in advance!!!!
Too long for a comment but a code-free answer...
Actually, I think what you want is to have a single login.php page, which processes the user login. On that page, first ensure username/password match. Then look up rights level to see if they are an admin or a player (or something else in the future?). Set a session variable to indicated user is authenticated and a user rights level - admin or player (this gives future flexibility to add "moderator", etc)
On admin.php check the session to see that the user is authenticated, and the user has admin rights. If they don't then unset all the session variables and redirect to the home page or login page. If you want to be nice, before doing that check to see if they are an authenticated user and if so redirect to game.php instead.
On game.php check the session to see that the user is authenticated, and the user does not have admin rights. If they do have admin rights, print a message reminding that admins can't play while logged in as admins, and provide a link to admin.php and logout.php (which will unset all session vars and redirect to login.php). Then check to make sure you have an authenticated gamer, if not then bounce to the logout.php (and again back to login.php) also.
I am running a simple service where users have to login to be able to operate special functonalities.
My MySQL database stores the username, password and user_id.
When user wants to login, they must provide their username and password which are posted to profile.php.
The profile.php does a simple check:
// Sanity Check
if(empty($_POST['smart_email'])|| empty($_POST['smart_password']))
{
echo 'Sorry, wrong login/passwd';
exit;
}
else
{
//
$smart_email = $_POST['smart_email'];
$smart_password=$_POST['smart_password'];
// Check if registerd and password matches
if(DB_IsAuthorized($smart_email, $smart_password) == true)
{
// Obtain proper UserID from the database
$UserID = DB_GetId($smart_email);
// set the session user_id variable
$_SESSION['user_id'] = $UserID;
//
// Display the User profile page
//
}
}
From that moment, every single page that is user-related has a check for user_id set in $_SESSION to find out if this user was logged in and is authorized.
if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']) && $_SESSION['user_id']>0)
{
// USER IS LOGGED IN
}
The question is: Is this $_SESSION['user_id'] check enough to secure the pages from NON LOGGED IN USERS ?
This question is too broad but simple answer is no.
Firstly, you will need https to make sure you protect users from hackers by using firewalls and other required security tools.
Secondly, you need to use htaccess to change extensions, say show user .html instead of .php
Thirdly, Sessions can be hijacked easy by hackers. So always try to store encrypted session values instead of plain text.
There are a lot more issues to take care of but its too complex and broad.
I am doing a web-application using PHP for job searching.
I have one query; when user is not logged in and wants to apply for the job given by clicking 'apply' button, he redirects to the login page. If the user is logged in when clicking, he should get directly to the application page. I'm not sure how to implement this.
I'm confused because I'm new to PHP.
Your question is very vague - maybe start with Authentication in PHP
Well, when the user clicks on 'apply' in your application the user is redirected to the login page if he is not logged in(which you can check if user session exists or not), remember when you redirect the page send the url of the current page in parameters to your login page so that when the user logs in he can be redirected back to the previous page and click on apply for that particular job.....
This is how the logic works, if you want the php, mysql explanation it would take some time for you to understand as you yourself conceded you are new to php..
You could store a value in the Session called "Login" and set this when the user logs in. This can also be used to re-direct the user if they haven't been logged in:
<?php
// check that the session variable does exist
// check that the user 'LoggedIn' has been set to 1 (true)
if (!isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] != 1)
{
// redirect to login page for user to authenticate themselves.
// pass page location (with parameters if necessary) to redirect
// the user on successful login.
header("Location: Login.php?redir=ApplyForJob.php?JobID=12345");
}
else
{
// user is logged in
// redirect the user directly to the apply for job page.
header("Location: ApplyForJob.php?JobID=12345");
}
?>
Can you, when the user logs in, assigns a $_Session variable to that user? i.e., after authentication, you set the $_SESSION['user'] variable.
$_SESSION['user']='admin';
So if you want to check whether the user is already log in after that, just use this:
if(isset($_SESSION['user']))
{
// user is login, direct to the job page
}
else
{
// no login, go to the login page
}
On each page set a cookie or session to which page they were just on:
$expire=time()+60*60*24*30;
setcookie("wherewasi","",time() - 1000);
setcookie("wherewasi",$_SERVER['REQUEST_URI'], $expire);
Then after login redirect them:
$loc = ($_COOKIE['wherewasi'])?$_COOKIE['wherewasi']:'index.php';
header("location: ".$loc);
exit();
There are two things that you need to worry about... checking that they've logged in, and then once they've logged in, directing them to the correct page.
This is all about 'saving state' across page requests. To do this you need can use cookies or more usefully sessions (which may be done via cookies or handled by the PHP engine for you automatically).
Sessions are probably a good way to go. To use sessions, every page needs to start with a
<?php session_start(); ?>
at the very least, before any html code that writes to the browser.
Once that's done you can use your the session variable to store
<?php $_SESSION['user']='joe_blow'; ?>
(and check)
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!='' {
// do something
}
?>
whether the user is logged in, and which page they need to be redirected to after login.
<?php header("location: ".$_SESSION['redirect_location']));
But in order to write the any more useful code I think people would need to know what authentication method you were using... (How are you doing your login? Are you storing ID's in a database? Are you using an off-the-shelf package?)
After I authenticate user login info, i create this session for them:
$_SESSION['username']= $userName;
Then, I redirect them like this:
header('Location:www.domain.com/profile/' . $_SESSION['username'];
I want my website to have a beauty URL, something like: www.domain.com/profile/userName
Thus, in all my redirect links (HTML <a> tag or PHP header() function), I will use:
"www.domain.com/album/" . $_SESSION['username'];
Are there any security loopholes?
Edit:
Do I need to create session id first using session_id()?
So, to check:
if(!isset($_SESSION['id']){
//redirect to login page
}
Normally while using Sessions we also need to be aware of -:
Session Hijacking , Session Fixation
I suggest in your code after user logged in store the username in session variable also store one more unique value such as USER AGENT in a session variable. so that every page the user visit we can check for whether the same USER AGENT and SESSION ID exist this would make it much secure. To make it much more secure do the encryption like MD% on User AGENT so that hackers cant reproduce it.
Quoted from PHP SECURITY GUIDE
<?php
session_start();
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
/* Prompt for password */
exit;
}
}
else
{
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
?>
Refer :
PHP Security Guide on Session
Another Thread on Session security
What are you protecting? What are you doing to verify that they have authorization? Are you protecting their profile and verifying that they have authorization because they have the session key? You don't ever mention checking that they have a session variable.
You won't even need to know the session ID. That is immaterial to storing whether the user has gotten authentication, that's just the mechanism which indicates what session information they should be using.
When the user logs in, you want to store something like
$_SESSION['authed_user'] = true;
And then, on subsequent attempts to edit information you do:
if ($_SESSION['authed_user']) {
// do something authed users can do
}
And naturally, you'll really probably want some sort of levels of authorization. I recommend you consider using something like SimpleAuth...
You need authorization on the page that allows user to edit their profile. If they'll be editing on the http://www.domain.com/profile/[username] page then you need to check if their $_SESSION['username'] is equal to the profile page they are on.
Otherwise anyone would be able to type in the URL (basically guess a profile number or name) and edit it.
But yes, you should first check if they've logged in AT ALL:
if (IsSet($_SESSION['username'])) {
// Logged in
} else {
// Not logged in
}