Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict direct page access

In attempt of securing an administrator area of a site I'm working on I made an index.php which contains

if (isset($_POST['password']) && isset($_POST['userName'])) {
        if($_POST['password']==$pass && $_POST['userName']==$username)
        {
            header( 'Location: admin.php' ) ;
        }

This redirects to a file in the same folder called admin.php. The problem is that I can access this file if I write localhost/folder/admin.php. Please tell me how to restrict the direct access to this page. The only way accesing it should be from index.php after username and password.

like image 641
George Avatar asked Jul 28 '11 23:07

George


2 Answers

set a session variable and check it everytimes somebody access admin.php

<?php
  if (isset($_POST['password']) && isset($_POST['userName'])) {
      if ($_POST['password'] == $pass && $_POST['userName'] == $username) {
          if (!session_id())
              session_start();
          $_SESSION['logon'] = true;

          header('Location: admin.php');
          die();
      }
?>

and

//admin.php 

if (!session_id()) session_start();
if (!$_SESSION['logon']){ 
    header("Location:index.php");
    die();
}
like image 187
genesis Avatar answered Oct 03 '22 21:10

genesis


You should look into PHP sessions. You can set a session variable "isLogged" in that redirection file, and then check in admin.php if that session variable is registered, if not redirect to the login page!

session_start();
if (isset($_POST['password']) && isset($_POST['userName'])) {
        if($_POST['password']==$pass && $_POST['userName']==$username)
        {
            header( 'Location: admin.php' ) ;
            $_SESSION['isLogged'] = true;
        }

admin.php

session_start();
if(!$_SESSION['isLogged']) {
  header("location:login.php"); 
  die(); 
}

Note: session_start(); must be called before the $_SESSION global can be utilised.

like image 27
Brad Morris Avatar answered Oct 03 '22 23:10

Brad Morris