开发者

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.


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();
}


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.


Set a session value that signifies that a user has successfully logged in, check for it on every page you want secured, redirect to login if that value isn't set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜