2014-10-03 83 views
-1

我有一个登录功能,我想返回一个变量的值,如果假$变量值:PHP函数返回虚假和不工作

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; 

这是的process_login

// 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"); 
} 

我想要函数返回错误变量的值,但它不起作用。

怎么回事?

谢谢!

+0

我缺少的东西,它会只能传递?如果你想返回错误变量的值,使用'return $ error;'。 – Barmar 2014-10-03 22:50:18

+0

最佳实践:不要告诉用户它的用户名或密码是否有误。如果你发出太多的信息,攻击者可以集中攻击。如果登录失败,只需从函数中返回'false'即可。 – 2014-10-03 22:51:39

+0

你说得对,谢谢你的提示! – 2014-10-03 22:54:18

回答

0

如前所述,我们不应让用户知道用户名或密码错误。 但这只是一个练习(我仍然开始使用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; 
} 

无需进行比较,如果登录()返回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"); 
} 
0

这应该做的伎俩:)

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


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

} 
+0

谢谢,但我已经尝试过,因为一些未知的原因将我重定向到索引...和idk如果有什么关系.htaccess重定向到index.php(我正在使用动态包括,我需要它) – 2014-10-03 22:59:24

0

你不能有两个相同的其他条件if语句,你应该返回变量$错误,而不是返回false,如果你真的需要知道的错误数量,但只为你所知。正如一位用户告诉你,尽量不告诉用户登录错误到底在哪里。只要告诉客户登录/密码的详细信息不正确

+0

它是一个旧的和不好的缩进代码(如果仔细观察,你会看到两个if语句)。这仅仅是我在学习php时的一个练习。无论如何,我会回答我自己的问题。 – 2016-01-17 16:23:26