Prevent user from accessing admin page - php

I have a php login page with session control. It routes a normal user to info.php and an admin user to info_admin.php. If I login with a "normal" user it goes to info.php, however, in the address bar, I can go to info_admin.php and it doesn't kick me out, gives me access. How can I control this or prevent the user from doing this manually?
For info, I'm using this script: http://php-login-script.com/
Thanks very much!

Just to make Lotus Notes' code a bit more compact:
<?php
if (!isset($_SESSION['user_level']) || ($_SESSION['user_level'] != 2)) {
header('Location: login.php');
exit;
}
?>
<!-- Your page HTML here -->

I quickly scanned through the login code, it seems to be setting a variable $_SESSION['user_level'] when the user first logs in.
To allow only user with level 2, for example, put this at the top of your page. It should redirect anyone who is not a level 2 user back to the login page.
<?php
if (isset($_SESSION['user_level'] && $_SESSION['user_level'] == 2) {
?>
<!-- Your page HTML here -->
<?php
} else {
header('Location: login.php');
}
?>

The high level approach is that upon login, store the user's access level in the session or in a database. At each page call, check against that value.

Just add an extra function that checks user level--if it's at or above the desired level, return true. If not, return false and failover. Then in your page you want to protect, fire the function with the desired level of protection.
For instance:
function checkPerms($level) {
if ($level >= number) {
return true
} else {
failover here
}
}
then call in your pages
checkperms(5);
EDIT: If you were really slick, you could just add an extra param to your original function call with the user level, defaulted to the lowest value. Then, if the user validates as registered, it could check the user level at the same time.

Related

How to prevent a user from directly accessing my html page by writing URL?

i want a hard coded Login Page (login.html), with no database.
If a person writes correct username and password, it redirects to (page2.html).
Now my problem is that if a person write the URL directly for page2.html , he will be able to access it, without any login.
Ideal Case => www.example.com/login.html => if Correct => www.example.com/page2.html
Problem Case => www.example.com/page2.html => page2.html , NO LogIN :(
You can control all this with a php session like this
//set the session on the login page
$_SESSION['loggedIn'] = true;
//on the second page you check if that session is true, else redirect to the login page
if($_SESSION['loggedIn'])
//allow
else
//redirect to the login page
header('Location: /login.html');
A session is a way to store information (in variables) to be used across multiple pages. By default, session variables last until the user closes the browser.
To make things simple, you can change your pages into php (e.g login.php).
Line 1: In your login.php page, you will first check if the username and password are correct, if they are, set the $_SESSION['loggedIn'] = true
Line 2: In your second page (page2.php), you will first check that the user did login by checking if the session have a value if($_SESSION['loggedIn']) {//allow processing}
Line 3: If that session variable is empty, then this means the user did not login, redirect him to the login page else { header('Location:/login.php');}
To start off: I have no idea how you would like to compare the password and username with something and check whether it's correct or not, but for now I would do something like this (again, this is without database).
You have 2 options: Either use a session as stated above, or the bit easier way: Just use theisset() function.
<form action="page2.php" method="POST">
<input type="text" name="userName" required>
<input type="password" name="password" required>
<button type="submit" name="submit">Send!</button>
</form>
page2.php will contain the next code:
if(!isset($_POST['submit']) {
//direct back to a certain page, could look like this:
header('Location: xxx.php');
exit();
//exit() prevents the code from running, it litterly EXITS the code as soon as it hits that line.
} else {
//direct to page2.php
}
Let's break it down: Why did I use the extension .php? Because you cannot do this purely with HTML.
Why did I use (!isset()) instead of isset()? Because a good practice is to think in security first, you don't access an important area and THEN check whether someone has lethal weapons or not. You check first and then you allow him either in or denie access. This is a quite simple and common way to prevent someone from accessing your page with the URL, however a SESSION is better and a bit more experienced practice.
This problem cannot be solved with a pure HTML solution. Your question is tagged as php so I'll base my answer on that:
Post your form to a php script (such as login.php)
Script checks the login details and sets a cookie
page2.html must be php instead, and checks for the cookie before displaying the HTML
Another option is using HTTP authentication, see this article for a tutorial.
You could block that page's access from external locations in your server securtiy settings,
then send the html of that page to the browser on successful login with fil_get_contents('page2.htm') in php. the php is run on the server so the file request won't be from an external source. you could overwrite html on the page using javascript or you could echo the contents on an if in php that will show the normal page on else
eg
if(isset($_GET['Login'])
{
//check login details
//if(....) //put your login check logic here
{
echo file_get_contents('page2.html');
}
else
{
//normal page's code goes here
}
}
Note:how to set the file to disallow external access is outside the scope of my answer
I had the same problem and found this and it works perfectly: (in javascript)
Just put it at the top of the document.
var x = document.referrer;
if (x == "page2.html") {
console.log(x);
} else {
window.location.href = "login.html";
};
change the default path for your website by using complete path to login.php. Next time when any of the user will type your url, they will be redirected to the given path which is yourpath>login.php
Hope it will help.
If you are using Asp.net, perhaps you can use TempData. They stay with the session between pages.
if (/*username and password are correct*/){
TempData["LoggedIn"] = "True";
} else {
TempData["LoggedIn"] = "False";
}
Then, when your controller tries to load page2 you just check the value of TempData.
var validate = TempData.Peek("LoggedIn");
if (validate == null || validate.ToString() == "False"){
return RedirectToAction("login");
} else {
/*allow access to page*/
}
Using .Peek keeps the TempData, as it would normally be marked for deletion if it was accessed. You also want to check it for null as it may have never been assigned if the user does not first go through the login page.
You can prevent that by checking if the user is already logged in
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
header('Location: login.php'); //here you put your login page
exit;
}

Two Steps to set Session as Logged In

I have a strange problem that does not set the user as logged in to the SESSION until a second click (although they are logged in)
So, I have a login dropdown that looks like this:
I send the user to the ACCOUNT-SELECTOR. PHP to determine the approprirate validation based on a business or individual account:
if (isset($_POST['loginAccountType']) && $_POST['loginAccountType'] == 'individual') {
include('ind_login.php');;
} elseif (isset($_POST['loginAccountType']) && $_POST['loginAccountType'] == 'business') {
include('bus_login.php');
} else {
include('error_login.php');
}
I have session_start(); on my account-selector.php page as well as my ind_login.php page. And, both are located at the very top of the page (before anything else).
Once I log in, this is my view:
As you can see, I am able to set and return the $_SESSION['Ind_ID'] on the ind_login.php page and VIEW YOUR PROFILE works (which is linked to the SESSION ID).
However, we still see a LOG IN button on the navigation when the code says this button should be set to display:none:
if(isset($_SESSION['Ind_ID'])) {
$accIndStyle = "visibility: visible;";
} else {
$accIndStyle = "display:none;";
}
I know this is the correct code as the button does become display: none for other buttons. However, if I log in a second time, or go to a different page with the session(start), the site will read the $_SESSION['Ind_ID'] as set and hide the Login button and replace it with a logout button.
Any help very much appreciated.
Put your session_start() on the top of your index.php file (That file which includes the others.)
seem like your page needs to be refreshed, or just throw an ajax call in there to update the button value according to session.

PHP Session (Login page and userpage)

I need to create a session on index page
if user already login in, it will header to member page.
if user destroy session, it will stay at index(login page)
what i did is
if(session_start){
header("location:member.php") or die();
}
if(isset($_POST['email']) && isset($_POST['password'])){
$email=strtolower($_POST['email']);
$password=md5($_POST['password']);
if($email && $password){
$connect=mysql_connect("localhost", "root", "");
$database=mysql_select_db("phplogin", $connect);
$SQL=mysql_query("SELECT * FROM users WHERE email='$email'");
$numrows=mysql_num_rows($SQL);
if($numrows!=0){
while($result=mysql_fetch_assoc($SQL)){
$db_email=$result['email'];
$db_password=$result['password'];
$db_firstname=$result['firstname'];
$db_lastname=$result['lastname'];
}
}
else{
die("Can't find the user");
}
if($email==$db_email && $password==$db_password){
session_start();
$_SESSION['firstname']=$db_firstname;
$_SESSION['lastname']=$db_lastname;
header("location:member.php");
}
else{
die("wrong username or password");
}
}
else{die("Please enter email or password");}
}
This works when user haven't destroy session, but when user destroy session
it didn't stay at index page
I need something like facebook, yet I don't know how facebook can share same the domain name on login page and user page.
so everytime i type facebook.com i will go to my user page, if i logout, it will become login page
You have used if(session_start). session_start() is a function. And it is used on each and every page. So it will redirect you everytime.
Another thing, you need to session_start() on the page you are storing the session and the page you are getting session values.
Instead of:
if(session_start){
header("location:member.php") or die();
}
Use:
session_start();
if(isset($_SESSION['firstname']) && isset($_SESSION['lastname'])){
header('location:member.php');
}
//and REMOVE session_start(); from where you have written.
How about on top of your page
if(!isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])){
header("location:index.php") or die();
}
First of all; only checking if a session exists isn't enough if you want to check if your user is logged in (the session could exist all the same, even if the user isn't logged in). So you should write a is_logged_in() function (or something like that) first to properly check the logged in status.
The reason why your user is always redirected is because the function session_start() returns true if a session is started succesfully; if the session is destroyed, it just starts a new one. So basically it will return true pretty much always, if everything works correctly (like user has not turned cookies off etc.).
If you have written that function it's actually quite simple. Let's pretend you have two files: home.php and member.php. The first one is your homepage (with a "Hello visitor!" message and the login form), the second is the member page. If both files are 'standalone' scripts you can indeed header the user to the specific page (header('Location: home.php'); if user should login first, header('Location: member.php'); if user is already logged in).
But! If you want to 'cloak' the pages (pretty much like facebook does it), you can just include the files in your index.php. Do something like this:
if(is_logged_in()) {
require_once('member.php'); // present member profile page
} else {
require_once('home.php'); // present login page
}
In your index.php you can set a constant (see also the php manual about constants) to be sure the files can only be included from within index.php:
--- index.php:
define('VALID_INCLUDE', true);
// the rest of your code
--- home.php & member.php:
if(!defined('VALID_INCLUDE')) die('You should not request this page directly');
But please note that if you want to write applications like this, a framework could help you a lot; it covers a lot if this kind of problems and makes coding a lot faster (most frameworks come with a authentication modules of some sort, and allow you to use 'views' to present your user with the proper pages, like I have done above with the require_once solution).

Loading a page when logging in and only when logging in

I have a login page that when you login in successfully you will be redirected to a page called gallery.html. However, when you type in the url with /gallery.html it will take you to the page that im trying to secure with logging in. What's the best way to use a conditional statement to prevent the page from being opened by typing in the exact URL? like a check before the page starts to load,
Simple, Use session variable on log-in, redirect the user to gallery.html if the session id is set, otherwise redirect to login page, something like this
if($_SESSION['userid']){
header( 'Location: gallery.html' ) ;
exit();
}elseif($_SESSION['userid'] == ''){
header( 'Location: login.html' ) ;
exit();
}
I like to create a function to handle this kind of thing:
function loggedin() {
if ( isset($_SESSION['user_id']) ) {
return true;
} else {
return false;
}
}
Or something shorter using a ternary operator:
function loggedin() {
return (isset($_SESSION['user_id'])) ? true : false;
}
Now to make the check, simply call the function within an if statement:
if ( loggedin() ) {
// only logged in users can see this
}
OR
if ( !logged_in() ) {
// only users who aren't looged in can see this
}
Much easier than typing something like if (!isset($_SESSION['user_id'])) { every time!
if you want to not show gallery.html to anonymous user, use this code at top of page
if(!isset($_SESSION['your_user_login_id']))
{
//redirect to home page
}
this code will prevent from anonymous user to view this page.
Use $_SESSION variable in gallery.php to check if the $_SESSION is set.
Although, I believe you will have to change the file name from gallery.html to gallery.php
<?php
if (!isset($_SESSION['secret_variable'])
{
echo "<br/>Error Message<br/>";
return;
}
?>
Continue with the rest of the code. If the user access the gallery.php by specifying the URL, he/she will end up with Error Message.
The $_SESSION['secret_variable'] should be set after you figure out that the user has a valid username and password to ensure a valid login.
Thanks.. :)
You need to set your login status in sessions and check for the session in your to-be-secured pages.
<?php
session_start();
if (!isset($_SESSION['login_status'])) {
// Add permission denied message or redirect back to the login page
}
?>
However, this can be done in PHP pages, not in a page with .html extenstion (unless you have explicitly specified your web server configuration with an "AddType x-httpd-php .html" directive.)
Easiest way is using php. Save your gallery.html as gallery.php or enter below code on top of the gallery.html page before all the coding. Then use a SESSION variable ($_SESSION['userID'] in here) to store current login details.
<?php
if(! isset($_SESSION['userID'])){ //userID or something to identify the user
header('Location:login.php'); //redirects to the login page
}else{
header('Location:gallery.php'); //redirect to the gallery.php for valid login
}
?>
There is no way of preventing someone from typing in the URL and requesting the page. THe only thing you'll be able to do is check if they are logged in on the page itself.
You have to set the cookie or session once the user is logging in. so you will set the session or cookie for the user. Every time while entering that particular url you have to check the session for showing that page or else redirect to the login page

Check whether user is logged in or not

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?)

Categories