Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php函数返回false和$variable值无效_Php_Function_Variables_Return - Fatal编程技术网

php函数返回false和$variable值无效

php函数返回false和$variable值无效,php,function,variables,return,Php,Function,Variables,Return,我有一个登录函数,如果为false,我希望返回一个变量值: function login($email, $password, $mysqli) { [...] // check if username exists if ($stmt->num_rows == 1) { // check if ($db_password == $password) { //check } else { // Invalid password $error = '2';

我有一个登录函数,如果为false,我希望返回一个变量值:

function login($email, $password, $mysqli) {
[...]
// check if username exists
if ($stmt->num_rows == 1) {
    // check
if ($db_password == $password) {
    //check
} else {
    // Invalid password
    $error = '2';
    return false;
} else {
        // No user exists.
        $error = '1';
        return false;
这就是登录的过程

// the login function is included in this page
if (login($email, $password, $mysqli) == true) {
    // Login success
    header('Location: /index.php');
} else {
    // Login failed
    header("Location: /login.php?error=$error");
}
我希望函数返回error变量的值,但它不起作用

怎么了

谢谢

这应该可以做到:)


在同一if语句中不能有两个else条件,如果确实需要知道错误号,但只需要知道已知的错误号,则应返回变量$error,而不是返回false。正如一位用户告诉您的,不要告诉用户登录错误的确切位置。只需告诉客户端登录/密码详细信息不正确

如前所述,我们不应让用户知道用户名或密码是否错误。 但这只是一个练习(我仍然在乞求php)

我们可以安全地移除另外两个

function login($email, $password, $mysqli) {
    [...]
    $exit = false;
    // check if username exists
    if ($stmt->num_rows > 0) {
        // check
        if ($db_password == $password) {
            // checked
            $exit = true;
        } else {
            // Invalid password
            $exit = 2;
        }
    } else {
        // No user exists.
        $exit = 1;
    }

    return $exit;
}
不需要比较,只有login()返回true时才会通过

// the login function is included in this page
if (login($email, $password, $mysqli)) {
    // Login success
    header('Location: /index.php');
} else {
    // Login failed
    header("Location: /login.php?error=$error");
}

我错过什么了吗?如果要返回错误变量的值,请使用
return$error。最佳做法:不要告诉用户是用户名还是密码出错。如果您提供的信息太多,攻击者可以集中攻击。如果登录失败,只需从函数返回
false
。你说得对,谢谢你的提示!谢谢,但我已经试过了,不知什么原因正在将我重定向到索引。。。idk if与.htaccess重定向到index.php有关(我正在使用dynamic includes,我需要它),这是一个旧的、不好的缩进代码(如果仔细看,您会看到两个if语句)。这只是我还在学习php时的一个练习。我会回答我自己的问题,谢谢你。
// the login function is included in this page
if (login($email, $password, $mysqli)) {
    // Login success
    header('Location: /index.php');
} else {
    // Login failed
    header("Location: /login.php?error=$error");
}