PHP中的简单密码保护

Lat*_*tze 2 php passwords

我正在阅读我的"学习PHP"一书中一个非常有趣的章节,并且遇到了我想在我的个人网站上修改和使用的代码示例(为了保护一个简单的文档,没有什么"大",这就是为什么我也不加密密码).

我已经使用了php-sample,但我根本无法使用它.
在这里(不要被长度吓到,它真的很简单):

<?php

if ($_POST['_submit_check']) {
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    } else {
        process_form();
    }
} else {
    show_form();
}

function show_form($errors = '') {
    echo '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';

    if ($errors) {
        echo '<br>'
        echo implode('<br>', $errors);
        echo '<br>';
    }

    echo 'Username: ';
    echo '<input type="text" name="username" value="Username goes here">';
    echo '<br>'

    echo 'Password: ';
    echo '<input type="password" name="password">';
    echo '<br>'

    echo '<input type="submit" name="submit" value="Log In">';
    echo '<input type="hidden" name="_submit_check" value="1">'; //when the form is entered, this returns true and the first line of the document is good to go

    echo '</form>';
}

function validate_form() {
    $errors = array();

    $users = array('admin' => 'pass123',
                   'notsoadmin' => 'pass1234');


    if (!array_key_exists($_POST['username']) {
        $errors[] = "Please enter username and password";
    }

    $saved_password = $users[ $_POST['password'] ];
    if ($saved_password != $_POST['password']) {
        echo "Password and username don't match. Please try again";
    }

    return $errors;
}

function process_form() {
    $_SESSION['username'] = $_POST['username'];

    echo "Welcome, $_SESSION[username]";
}

?>
Run Code Online (Sandbox Code Playgroud)

在我的HTML和东西之前我还添加了这个:

<?php session_start(); ?>
Run Code Online (Sandbox Code Playgroud)

很明显我错过了一些东西......也许它$form_errors在一开始就是正确的,这导致了问题(这是"没有发生"),它出现在我的书中,但我不确定它为什么/它来自哪里?

iri*_*uzz 5

不应该...

    $saved_password = $users[ $_POST['password'] ];
    if ($saved_password != $_POST['password']) {
        ...
    }
Run Code Online (Sandbox Code Playgroud)

实际上......

    $saved_password = $users[ $_POST['username'] ];
    if ($saved_password != $_POST['password']) {
        ...
    }
Run Code Online (Sandbox Code Playgroud)

即你应该寻找用户名输入而$users不是密码

By the way it's really bad practice to store raw passwords like that. Consider HASHing and SALTing them.

Check this question out for information