PHP Login with Username/Password

梦想的初衷 提交于 2019-12-06 14:52:06

Try this:

--------------------------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";
}
?>

Output:

Password incorrect, error, redirecting to login

But if you change the value of $_POST['password'] to 'pass1', like this:

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

You have this output:

welcome back username1

Saludos ;)

if it is only two users that should not be hard to get around, you can do something as follows;

 <?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
}

}
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!