2013-07-04 2 views
2

Я сделал страницу входа на мой сайт. Если идентификатор пользователя и пароль совпадают в базе данных, пользователь перенаправляется на page1.php, но если пользователь знает URL-адрес для page1.php, он может обойти страницу входа. Как решить эту проблему? Я знаю, что проблема такая тривиальная, но я новичок в веб-разработке и не могу найти решение этой проблемы. Кажется, что решение использует маркер визирования. Но я понятия не имею, как использовать его, чтобы запретить доступ или напрямую загрузить page1.phpНесанкционированный доступ к веб-странице

<?php 

/*** begin our session ***/ 
session_start(); 

/*** set a form token ***/ 
$form_token = md5(uniqid('auth', true)); 

/*** set the session form token ***/ 
$_SESSION['form_token'] = $form_token; 
?> 


<!DOCTYPE html> 
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> 
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]--> 
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]--> 
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]--> 
<head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <link rel="stylesheet" href="css/style.css"> 
    <!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]--> 
</head> 
<body> 

    <form method="post" action="login.php" class="login"> 
    <p> 
     <label for="username">Username:</label> 
     <input type="text" name="username" id="username" style="width:300px" required placeholder="enter username" maxlength="20"> 
    </p> 

    <p> 
     <label for="password">Password:</label> 
     <input type="password" name="password" id="password" style="width:300px" required placeholder="enter password" maxlength="20"> 
    </p> 

    <p class="login-submit"> 
     <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /> 
     <button type="submit" class="login-button" value="&rarr; Login">Login</button> 
    </p> 

    <p class="forgot-password"><a href="index.html">Forgot your password?</a></p> 
    </form> 

    <sup style="color:#777; padding-left:550px;"> ** both username and password must be alpha-numeric between 4-20 characters</sup> 



</body> 
</html> 

Это мой файл PHP, который обрабатывает форму Войти вход

<?php 

/*** begin our session ***/ 
session_start(); 

/*** check if the users is already logged in ***/ 
if(isset($_SESSION['user_id'])) 
{ 
    $message = 'Users is already logged in'; 
} 
/*** check that both the username, password have been submitted ***/ 
if(!isset($_POST['username'], $_POST['password'])) 
{ 
    $message = 'Please enter a valid username and password'; 
} 
/*** check the username is the correct length ***/ 
elseif (strlen($_POST['username']) > 20 || strlen($_POST['username']) < 4) 
{ 
    $message = 'Incorrect Length for Username'; 
} 
/*** check the password is the correct length ***/ 
elseif (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 4) 
{ 
    $message = 'Incorrect Length for Password'; 
} 
/*** check the username has only alpha numeric characters ***/ 
elseif (ctype_alnum($_POST['username']) != true) 
{ 
    /*** if there is no match ***/ 
    $message = "Username must be alpha numeric"; 
} 
/*** check the password has only alpha numeric characters ***/ 
elseif (ctype_alnum($_POST['password']) != true) 
{ 
     /*** if there is no match ***/ 
     $message = "Password must be alpha numeric"; 
} 
else 
{ 
    /*** if we are here the data is valid and we can insert it into database ***/ 
    $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING); 
    $password = filter_var($_POST['password'], FILTER_SANITIZE_STRING); 

    /*** now we can encrypt the password ***/ 
    // $password = sha1($password); 

    /*** connect to database ***/ 
    /*** mysql hostname ***/ 
    $mysql_hostname = 'localhost'; 

    /*** mysql username ***/ 
    $mysql_username = 'abcdefg'; 

    /*** mysql password ***/ 
    $mysql_password = 'abcdefg'; 

    /*** database name ***/ 
    $mysql_dbname = 'abcdefg'; 

    try 
    { 
     $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 
     /*** $message = a message saying we have connected ***/ 


     /*** set the error mode to excptions ***/ 
     $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

     /*** prepare the select statement ***/ 
     $stmt = $dbh->prepare("SELECT username, password FROM user 
        WHERE username = :username AND password = :password"); 

     /*** bind the parameters ***/ 
     $stmt->bindParam(':username', $username, PDO::PARAM_STR); 
     $stmt->bindParam(':password', $password, PDO::PARAM_STR, 40); 

     /*** execute the prepared statement ***/ 
     $stmt->execute(); 

     /*** check for a result ***/ 
     $user_id = $stmt->fetchColumn(); 

     echo $user_id; 
     /*** if we have no result then fail boat ***/ 
     if($user_id == false) 
     { 
       $message = 'Login Failed'; 
     } 
     /*** if we do have a result, all is well ***/ 
     else 
     { 
       /*** set the session user_id variable ***/ 
       $_SESSION['user_id'] = $user_id; 

       /*** tell the user we are logged in ***/ 
       $message = 'You are now logged in'; 
       echo '<script>window.location = "http://127.0.0.1/university/site/page1.php"</script>'; 

     } 


    } 
    catch(Exception $e) 
    { 
     /*** if we are here, something has gone wrong with the database ***/ 
     $message = 'We are unable to process your request. Please try again later"'; 
    } 
} 
?> 

<html> 
<head> 
<title> Login</title> 
</head> 
<body> 
<p><?php echo $message; ?> 
</body> 
</html> 

ответ

2

На каждой странице, что пользователь . потребности должны войти в систему, чтобы получить доступ, вы должны проверить, пользователю нужно войти в систему что-то вроде:

session_start(); 

// Check if user is logged in 
if(!isset($_SESSION['user_id'])) 
{ 
    // User is not logged in 
    $_SESSION['message'] = 'You\'re not logged in'; 

    // redirect to home page 
    header('Location: \'); 
    exit; 
} 

концепция называется Контроль доступа и есть много различных способов, которые вы можете сделать это. Мой маленький скрипт здесь прост, поэтому, в конце концов, вы, вероятно, захотите что-то более надежное.

+0

Я просто попробовал этот код в моей целевой странице, но он по-прежнему доступен, хотя я не вошли в систему. – akashaggarwaal

+0

Попробуйте очистить ваши куки. Может быть оставленный cookie, который отбрасывает его. – chrislondon

+0

yup, мой localhost сохранил сеансовые файлы cookie в браузере. Thanx за помощь :) – akashaggarwaal

1

Вы можете использовать Список контроля доступа, чтобы обеспечить более высокий уровень безопасности. Вот ссылка, где вы можете найти соответствующую информацию.

http://www.developer.com/lang/php/creating-a-custom-acl-in-php.html

<?php 
Class Acl { 

    private $db; 
private $user_empty = false; 

    //initialize the database object here 
    function __construct() { 
    $this->db = new db; 
    } 

    function check($permission,$userid,$group_id) { 

    //we check the user permissions first 
    If(!$this->user_permissions($permission,$userid)) { 
     return false; 
    } 

    if(!$this->group_permissions($permission,$group_id) & $this->IsUserEmpty()) { 
     return false; 
    } 

    return true; 

    } 

    function user_permissions($permission,$userid) { 
$this->db->q("SELECT COUNT(*) AS count FROM user_permissions WHERE permission_name='$permission' AND userid='$userid' "); 

$f = $this->db->f(); 

    If($f['count']>0) { 
    $this->db->q("SELECT * FROM user_permissions WHERE permission_name='$permission' AND userid='$userid' "); 

    $f = $this->db->f(); 

    If($f['permission_type']==0) { 
    return false; 
    } 

    return true; 

    } 
    $this->setUserEmpty('true'); 

    return true; 

    } 
function group_permissions($permission,$group_id) { 
$this->db->q("SELECT COUNT(*) AS count FROM group_permissions WHERE permission_name='$permission' AND group_id='$group_id' "); 

$f = $this->db->f(); 

    if($f['count']>0) { 
    $this->db->q("SELECT * FROM group_permissions WHERE permission_name='$permission' AND group_id='$group_id' "); 

    $f = $this->db->f(); 

    If($f['permission_type']==0) { 
    return false; 
    } 

    return true; 

    } 

    return true; 

    } 


    function setUserEmpty($val) { 
    $this->userEmpty = $val; 
} 

function isUserEmpty() { 
    return $this->userEmpty; 
} 


} 
?> 
Смежные вопросы