2

所以我正在开发一个小网站,我希望它只对我和我的朋友可见,因为我只是在开发它,而 .htaccess 不是我现在想要的。我对PHP不太好,我设法写了这个:

<?
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
if($user == "xxx1" or "xxx2" and $pass == "xxx1" or "xxx2"){
    setcookie("notrandom", "Success", time()+3600);
}
else{
    setcookie("notrandom", "Success", time()-3600);
}
header("Location:index.php");

将此放置在页面导航栏上,因此如果用户尚未登录,它将杀死页面的内容并且仅显示登录表单:

<?php 
if(empty($_COOKIE['notrandom'])){
    echo '
    <form class="form-inline navbar-form pull-right" method="post" action="kirjaudu.php">
  <input type="text" class="input-medium" placeholder="Käyttäjätunnus" name="user">
  <input type="password" class="input-medium" placeholder="Salasana" name="pass">

  <button type="submit" class="btn">Kirjaudu</button>
</form>
</div>
</div><!-- /navbar-inner -->
</div>
    ';
    die();
}

?>

但是,我的问题是脚本将接受输入的任何用户名和密码,所以我在这里误用orand吗?

我应该怎么做?我将如何使用它?

$user = array("User1"=>"Pass1", 
              "User2"=>"Pass2");
4

4 回答 4

3

你在做什么:

当你这样做时($user == "xxx1" or "xxx2"),你实际上在做的是与 比较$user"xxx1"然后,OR'ing"xxx2",产生TRUE。你的条件不正确。

运算符优先级


使固定:

它应该是:

if(($user == "xxx1" and $pass == "xxx1") or ($user == "xxx2" and $pass == "xxx2")){
...
...
}

这将评估TRUE

case1: username = xxx1, password = xxx1
case2: username = xxx2, password = xxx2
于 2012-11-09T06:36:32.440 回答
0

试试这个代码:

<?
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];

if(($user == "xxx1" && $pass == "xxx1") || ($user == "xxx2" && $pass == "xxx2")){
     setcookie("notrandom", "Success", time()+3600);
}
else{
     setcookie("notrandom", "Success", time()-3600);
}
header("Location:index.php");
?>
于 2012-11-09T06:38:46.750 回答
0

这个声明并没有像你认为的那样做:

if($user == "xxx1" or "xxx2" and $pass == "xxx1" or "xxx2")

真的很像写:

if ($user=="xxx1" or ("xxx2" != false and $pass == "xxx1") or "xxx2" != false)

所以这个陈述总是正确的,因为“xxx2”永远不会是错误的。

你想要的是:

if ( ($user=="xxx1" and $pass=="xxx1") or ($user=="xxx2" and $pass=="xxx2") )

您可以使用包含任意数量的用户名/密码的数组。只需确保在尝试比较其值之前检查以确保用户密钥存在:

$userArray = array("User1"=>"Pass1", "User2"=>"Pass2");

if (array_key_exists($user, $userArray) && $userArray[$user] == $pass) {
    // user is logged in!
} else {
    // user is not logged in
}

您的 cookie 仍有问题。为什么不只使用会话:

session_start();
if (array_key_exists($user, $userArray) && $userArray[$user] == $pass) {
    $_SESSION['loggedIn'] = true;
} else if (!isset($_SESSION['loggedIn']) {
    $_SESSION['loggedIn'] = false;
}

// then later whenever you want to detect if the user is logged in or not...

if ($_SESSION['loggedIn']) { 
    // ... do stuff ...
}
于 2012-11-09T06:41:17.517 回答
0

试试这个,执行起来可能会更快,避免不必要的比较

<?
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];

if($user == "xxx1" && $pass == "xxx1") {
     setcookie("notrandom", "Success", time()+3600);
}
else if($user == "xxx2" && $pass == "xxx2){
setcookie("notrandom", "Success", time()+3600);
}
else{
     setcookie("notrandom", "Success", time()-3600);
}
header("Location:index.php");
?>
于 2012-11-09T07:01:00.107 回答