簡體   English   中英

我正在嘗試制作一個登錄頁面。 然而,事情總是出錯 - 我不知道是什么?

[英]I am trying to make a login page. However something keeps going wrong - and I don't know what?

我是 PHP 的新手,我一直在學習如何制作注冊/登錄頁面的課程。 我已成功完成注冊頁面,但登錄頁面給我帶來了問題。 這是我的登錄代碼。php:

<?php
include_once '../resources/session.php';
include_once '../resources/database.php';
include_once '../resources/utilities.php';

if(isset($_POST['loginBtn'])){

    // array to hold errors
    $form_errors = array();

    // validate
    $required_fields = array('username ', 'password ');

    $form_errors = array_merge($form_errors, check_empty_fields($required_fields));

    if(empty($form_errors)){

        // collect form data
        $user = $_POST['username'];
        $password = $_POST['password'];

        //  check if user exists in the database
        $sqlQuery = "SELECT * FROM users WHERE username = :username";
        $statement = $db->prepare($sqlQuery);
        $statement->execute(array(':username' => $user));

        while($row = $statement->fetch()){
            $id = $row['id'];
            $hashedpassword = $row['password'];
            $username = $row['username'];

            if(password_verify($password, $hashed_password)){
                $_SESSION['id'] = $id;
                $_SESSION['username'] = $username;
                header("location: dashboard.php");
            }
            else{
                $result ="<p style='padding: 20px; color: red; border: 1px solid gray;'> Invalid username or password</p>";
            }
        }

    }
    else{
        if(count($form_errors) == 1){
            $result = "<p style='color:red;'>There was 1 error in the form</p>";
        }
        else{
            $result = "<p style='color:red;'> There were " .count($form_errors). " errors in the form </p>";
        }
    }
}

?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Login</title>
        <link rel="stylesheet" href="../css/indexstyles.css">
    </head>
    <body>

        <h2>Login Form</h2>
        <?php if(isset($result)) echo $result; ?>
        <?php if(!empty($form_errors)) echo show_errors($form_errors); ?>
        <form action="" method="post">
            <table>
                <tr>
                    <td>Username:</td>
                    <td><input type="text" value="" name="username "></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input type="password" value="" name="password "></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input style="float: right;" = type="submit" name="loginBtn" value="Login"></td>
                </tr>
            </table>
        </form>
</html>

我的 database.php 代碼是:

<?php

// intialize variables to hold connection parameters
$username = 'root';
$dsn = 'mysql:host=localhost; dbname=register';
$password = 'xxxx';


try{
    // create an instance of the PDO class with the required parameters
    $db = new PDO($dsn, $username, $password);

    // set PDO error mode to exception
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // display success message
    // echo "Connected to the register database";

}catch (PDOException $ex){

    // display error message
    echo "Connection unsuccesful. ERROR: ".$ex->getMessage();
}

我的實用程序代碼。php 是這樣的:

<?php

/**
    * @param $required_fields_array, n array containing the list of all required fields
    * @return array, containing all errors
*/

// start

 function check_empty_fields($required_fields_array){
        // initialize an array to store error messages
        $form_errors = array();

        // loop throgh the required fields array and popular the form error array
        foreach ($required_fields_array as $name_of_field){
            if(!isset($_POST[$name_of_field]) || $_POST[$name_of_field] == NULL){
                $form_errors[] = $name_of_field . "is a required field";

            }

        }

        return $form_errors;
}

/**
    * @param $fields_to_check_length, an array containing the name of fields
    * for which we wnt th check min required length e.g. array('username' => 4, 'email' => 12)
    * @return array, containing all errors
*/

function check_min_length($fields_to_check_length){
    //initialize an array to store error messages
    $form_errors = array();

    foreach($fields_to_check_length as $name_of_field => $minimum_length_required){
        if(strlen(trim($_POST[$name_of_field])) < $minimum_lenth_required){
            $form_errors[] = $name_of_field . " is too short, must be {$minimum_length_required} characters long";

        }
    }
    return $form_errors;
}


/**
    * @param $data, store a key/value pair array where key is the name of the form control
    * in this case 'email' and value is the input entered by the user
    * @return array, containing email error
*/

function check_email($data){
    //initialize an array to store error messages
    $form_errors + array();
    $key = 'email';
    // check if the key email exists in data array
    if(array_key_exists($key, $data)){

        // check if the email field has a value
        if($_POST[$key] != null){

            // remove all illegal characters from email
            $key = filter_var($key, FILTER_SANITIZE_EMAIL);

            // check if input is a valid email addresss
            if(filter_var($_POST[$key], FILTER_VALIDATE_EMAIL) === false){
                $form_errors[] = $key . " is not a valid email address";
            }
        }
    }

    return $form_errors;
}

/**
    * @param $form_errors_array, the array holding all
    * errors which we want to loop through
    * @return string, list containing all error messages
*/

function show_errors($form_errors_array){
    $errors = "<p><ul style ='color: red;'>";

    // loop through error array and display all items in a list
    foreach($form_errors_array as $the_error){
        $errors .= "<li> {$the_error} </li>";
    }
    $errors .= "</ul><p>";
    return $errors;
}

最后,我的 session.php 是:

<?php
session_start();

當我按下登錄按鈕而不輸入任何內容時,我會收到預期的錯誤消息。 但是,如果我輸入我創建的模擬賬戶,我仍然會收到相同的錯誤消息。

任何幫助是極大的贊賞!

  • 西安娜

一個

您根據需要檢查的字段末尾包含空格:

$required_fields = array('username ', 'password ');

因此,這些名稱永遠不會存在於發布的數據中。 將該行更改為:

$required_fields = array('username', 'password');

它應該工作。

更新:我之前沒有注意到,但您的表單輸入在名稱末尾也有空格。 也從那里刪除空間。 當表單提交並在末尾有這些空格時,$_POST 包含“用戶名_”和“密碼_”。 即 PHP 將空格轉換為下划線。

如果您添加空格只是為了讓錯誤消息有一個空格,那么添加空格的正確位置將就在“是必填字段”之前,而不是在輸入名稱本身中。

請記住在進行更改后重新加載頁面。

暫無
暫無

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

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