通过PHP上的$ _SESSION进行用户验证

时间:2013-03-31 14:02:06

标签: php validation session

我正在尝试使用PHP上的$ _SESSION超全局验证用户,但似乎$ _Session不喜欢我,任何帮助都是值得赞赏的,我有以下代码叫做index.php:

 '<?php
 'session_start();
 'require("administratorcheck.php");
  //i have tried require_once "administratorcheck.php"
  '?>

在这种情况下,administratorcheck.php看起来像这样进行验证:

        <?php
      $errorMessage =  'Your Login Information Is Not Correct';
     if(isset($_POST['username'])){
     $username = $_POST['username'];
     $password = $_POST['password'];

    $adminUser = "admin";
    $adminPass = "donkeyKong";

if(($username!=$adminUser)||($password !=$adminPass))
{
   echo  $errorMessage;
}else{
// session_register('admin');
$_SESSION['admin'] = $username;
header("index.php");
exit();
}

}
 if(isset($_SESSION['admin'])!= 'admin')
 {
 echo '<h2>You Are Not Authorized To View This File</h2><br/>
 <table width = "400" border = "2">
 <form action = "administratorcheck.php" method="post" >
 <tr>
<td colspan = "2">You May Be Able To Login Here</td>
</tr>
 <tr>
<td width="108">Admin Username:</td>
<td width="250"><input type="text" name="username" id="username" style="width:98%"/>                                                            
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password" style="width:98%"/></td>
</tr>
 <tr>
<td colspan="2" align="center"><input type="submit" name="button" id="button" 

value="Log Me In"/></td>
</tr>
</form>
</table>
</br>
</br>
<a href = "../">Click Here To Return To The Index Page</a>';
exit();
 }

&GT;

2 个答案:

答案 0 :(得分:2)

问题

下面这行不是你认为它正在做的事情。

if(isset($_SESSION['admin'])!= 'admin')

如果你把它分成更小的部分,你会看到。查看第一部分,您会看到从isset

返回一个布尔值
$isAdminFieldSet = isset($_SESSION['admin']) // this returns a boolean

现在在你的if语句中你实际上在做

if($isAdminFieldSet != 'admin') {

真的是

if(true != 'admin') {

if (false != 'admin') {

解决方案

是管理员检查

if (isset($_SESSION['admin']) && $_SESSION['admin'] == 'admin')  {
   // user is an admin
   ...
}

不是管理员检查

if (!isset($_SESSION['admin']) || $_SESSION['admin'] != 'admin' )  {
   // user is not an admin
   ...
}

答案 1 :(得分:0)

if(isset($_SESSION['admin'])!= 'admin')

isset返回一个布尔值,因此永远不会等于'admin'