如何阻止两个会话同时运行' admin'和'用户'

时间:2016-05-19 13:45:42

标签: php

我无法让$_SESSION只创建useradmin会话。

这是帐户文件的内容:

User||1234||user admin||1234||admin

开始代码:

<?php session_start();?>
<?php
$username = $_POST['username']; 
$password = $_POST['password'];
$level;
$date = date("d.m.Y");`

当前代码:

if (isset($_POST['login'])){
    $file = explode(PHP_EOL, file_get_contents( "Users/accounts.txt" ));
    $auth = false;

foreach( $file as $line ) {
    list($username, $password, $level) = explode("||", $line);
    if ($_POST['username'] == $username && $_POST['password'] == $password) {
         $auth = true;
         break;
    }
}

 if($auth) {
    echo "Login successfull!";
    $data = "Login successfull" . "\t" . "Username: " . $_POST['username'] . " Password: " . $_POST['password'] . " Level: " . $level . " Date: " . $date . "\r\n";
    file_put_contents('Users/logs.txt', $data, FILE_APPEND);

    if($level = 'admin') {
        $_SESSION['admin']=$username;
        header('location: check.php');  
    }
    if($level = 'user') {
        $_SESSION['user']=$username;
        header('location: check.php');  
    }
} 
else {
    echo "Invalid username or password";

    $data = "invalid login" . "\t" . "Username: " . $_POST['username'] . " Password: " . $_POST['password'] . " Level: " . $level . " Date: " . $date . "\r\n";

    file_put_contents('Users/logs.txt', $data, FILE_APPEND);
    }
}
?>

Current form:

<form method="post">
<b>Username:</b><br>
<input type="text" name="username" /><br>                
<b>Password:</b><br>
<input type="password" name="password"/><br>
<input type="submit" value="Login" name="login"/>
<input type="reset" value="Reset" name="reset"/>
</form>`

请帮助,我已经尝试更改会话的名称和其他小事情,但我不能让它停止同时执行会话,因为我试图阻止某些会话访问某些页面。

1 个答案:

答案 0 :(得分:0)

如果你的意思是逐行读取文件,那么你应该这样做,当你读完整个文件,然后尝试使用$file = fopen("inputfile.txt", "r"); if ($file) { while (($line = fgets($file)) !== false) { list($username, $password, $level) = explode("||", $line); if ($_POST['username'] == $username && $_POST['password'] == $password) { $auth = true; break; } } 它效率非常低(显然不能做你想要的)。 这样做:

{{1}}