簡體   English   中英

為什么 else 語句在 php 的 foreach 循環中不起作用?

[英]Why is the else statement not working inside a foreach loop in php?

我正在構建一個腳本,可以幫助用戶在忘記密碼時重置密碼。 此特定腳本首先檢查用戶希望發送令牌的 email 是否存在。 如果是,則將令牌插入到令牌表中。

我還在開發和測試中,所以我還沒有創建郵件 function。

我有一個 if 語句來檢查 email 是否存在,然后創建令牌。 如果不存在,則顯示再次輸入 email 地址的頁面。 if 語句工作完美,但 else 不是。 我將整個文件粘貼在這里,盡管它只是與我們的問題有關的 foreach 語句的一部分。

else 語句完全沒有顯示任何內容。

<?php
    //generate tokens to verify users who forgot their passwords. Send these tokens to the user's email
    
    require $_SERVER['DOCUMENT_ROOT'] . "/phonebook/config.php";
    
    //get user's email
    $mail = htmlspecialchars($_POST['email']);
    //generate token
    $token = $token = openssl_random_pseudo_bytes(20);
    //Convert the binary data into something more readable
    $token = bin2hex($token);
    
    //check if the email entered exists
    $check = $conn->prepare("SELECT email FROM users WHERE email = :email");
    $check->bindParam(":email", $mail);
    $check->execute();
    
    foreach ($check as $confirm) {
        if ($confirm['email'] == $mail) {
            //send tokens to the database
            $sql = $conn->prepare("INSERT INTO tokens (email, token)
            VALUES(:email, :token)");
            
            $sql->bindParam(":email", $mail);
            $sql->bindParam(":token", $token);
            $sql->execute();
    
            echo "<h2>Enter security code</h2>
            A security code has been sent to the email addres $mail. Enter that code in the box below:
            <form action = 'http://localhost/phonebook/controls/forgotpassword.php' method = 'post'>
            <input type = 'hidden' name = 'email' value = '$mail'>
            <input type = 'text' name = 'token'> <br>
            <input type = 'submit' value = 'Reset password'>
            </form>
            Did not receive code? Go <a href = 'http://localhost/pages/forgotpassword.php'here</a>";
        } else {
            echo "That email does not exist. Please try again.";
            include_once "$paste/phonebook/pages/forgotpassword.php";
    }
}

在這里發現三個問題。

您將使用htmlspecialchars()編碼的$mail與可能未編碼的 email 地址進行比較。

您獲取多行而不是一行:

//check if the email entered exists
$check = $conn->prepare("SELECT email FROM users WHERE email = :email LIMIT 1");
$check->bindParam(":email", $mail);
$check->execute();

$confirm = $check->fetch()
if (isset($confirm['email']) && $confirm['email'] === $mail) {
    //send tokens to the database

您告訴“用戶”email 地址確實存在於您的系統中; 這是一個隱私和數據安全問題。 只需發送類似“如果輸入的 email 地址在我們的系統中,我們只需向它發送密碼重置鏈接。”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM