用户名/密码登录PHP

时间:2013-11-15 21:37:22

标签: php arrays session login username

如何编辑下面的PHP以允许其他或多个用户名和密码。例如,User1使用密码JHFDE3,User2使用密码LKFW34等。根据我的阅读,关联数组可能是最好的。没有数据库,只需登录就可以硬编码,并且能够查看php页面。

对于下面的特定代码,我如何将其转换为关联数组?谢谢。

<?php
session_start(); //initiates the sessions
if ($_POST['submit']) //checks to make sure the login form has been submitted
    {
    $user = "XXXXX";
    $pass = "XXXXXXX";
    if ($_POST['pass'] == $pass && $_POST['user'] == $user) //checks if the password submitted by the user matches the password stored in the $pass variable
        {
        $_SESSION['access'] = 1; //if login is successful create a session that can be authenticated 
        header("Location: " . $_SERVER['PHP_SELF']); //reload the page. The page will now not load the login form (see the first if condition)
    } else //if password is incorrect reload the login form
        {
        header("Location: " . $_SERVER['PHP_SELF']);
    }
} else if (!$_SESSION['access']) //if the "access" session is not accessible show the form (not logged in)
    {
?>

2 个答案:

答案 0 :(得分:1)

试试这个:

-------------------------- UPDATE -------------------- --------------

<?php
session_start(); //initiates the sessions

//begin testing
$_POST['user'] = 'username1';
$_POST['submit'] = true;
$_POST['password'] = 'pass3';
//end  testing

if (isset($_POST['submit'])) //checks to make sure the login form has been submitted
    {

    $users = array('username1','username2','username3');
    $passwords = array('pass1','pass2','pass3' );
    if(in_array($_POST['user'], $users))
    {
       $key = array_search($_POST['user'], $users);

       if($passwords[$key]==$_POST['password'])
       {
         $_SESSION['access'] = 1; //if login is successful create a session that can be authenticated 
         //header("Location: " . $_SERVER['PHP_SELF']);
         echo "welcome back ".$_POST['user'];
       } else //if password is incorrect reload the login form
        {
         //header("Location: " . $_SERVER['PHP_SELF']);
          echo "Password incorrect, error, redirecting to login";
        }


    }

    }
else 
{
  echo "Login form";
}
?>

输出:

Password incorrect, error, redirecting to login

但是如果你将$ _POST ['password']的值更改为'pass1',就像这样:

$_POST['password'] = 'pass1';

你有这个输出:

welcome back username1

Saludos;)

答案 1 :(得分:0)

如果只有两个用户不难解决,你可以采取以下措施;

 <?php
//change the variable values accordingly
$user1='user1';
$user2='user2';
$pass1='pass1';
$pass2='pass2';
if ($_POST['submit'])  {
//check if they are equal to your info
if(($_POST['user']==$user1) && $_POST['pass'] == $pass1){
        $_SESSION['access'] = 1; 
        header("Location: " . $_SERVER['PHP_SELF']); 
} else if(($_POST['user']==$user2) && $_POST['pass'] == $pass2){
        $_SESSION['access'] = 1; 
        header("Location: " . $_SERVER['PHP_SELF']); 
} else {//not valid at all
//do what you want for login fail
}

}
?>