• PHP 用户注册和登录表单 – PDO。


    这是关于如何使用 PHP 的 PDO 对象构建用户注册和登录表单的初学者教程。就目前而言,网络上有数百个“PHP 登录教程”。不幸的是,他们中的绝大多数使用现在被认为已经过时的不安全的密码散列方法和扩展(我在看着你,mysql_query)。

    用户表结构。

    通过使用非常基本的表结构,我使事情变得简单。显然,如果需要(电子邮件地址和姓名等),您可以对其进行自定义并将您自己的列添加到此表中。本教程假设我们的登录是基于用户名和密码组合(而不是电子邮件和密码组合)。您可以将以下表结构导入数据库:

    1. CREATE TABLE IF NOT EXISTS `users` (
    2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    3. `username` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
    4. `password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
    5. PRIMARY KEY (`id`),
    6. UNIQUE KEY `username` (`username`)
    7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

    注意:我在用户名列中添加了唯一索引。这是因为用户名必须是唯一的!

    连接。

    首要任务是使用 PDO 对象连接到 MySQL。有关这方面的更深入的教程,您应该阅读我的教程 “使用 PHP 连接到 MySQL”。出于本教程的目的,我创建了一个名为connect.php的文件,我们将在整个脚本中包含该文件:

    1. //connect.php
    2. /**
    3. * This script connects to MySQL using the PDO object.
    4. * This can be included in web pages where a database connection is needed.
    5. * Customize these to match your MySQL database connection details.
    6. * This info should be available from within your hosting panel.
    7. */
    8. //Our MySQL user account.
    9. define('MYSQL_USER', 'root');
    10. //Our MySQL password.
    11. define('MYSQL_PASSWORD', '');
    12. //The server that MySQL is located on.
    13. define('MYSQL_HOST', 'localhost');
    14. //The name of our database.
    15. define('MYSQL_DATABASE', 'test');
    16. /**
    17. * PDO options / configuration details.
    18. * I'm going to set the error mode to "Exceptions".
    19. * I'm also going to turn off emulated prepared statements.
    20. */
    21. $pdoOptions = array(
    22. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    23. PDO::ATTR_EMULATE_PREPARES => false
    24. );
    25. /**
    26. * Connect to MySQL and instantiate the PDO object.
    27. */
    28. $pdo = new PDO(
    29. "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
    30. MYSQL_USER, //Username
    31. MYSQL_PASSWORD, //Password
    32. $pdoOptions //Options
    33. );
    34. //The PDO object can now be used to query MySQL.

    上面的代码将使用 PDO 扩展连接到 MySQL 数据库。您将需要阅读代码中散布的注释并更改 MySQL 连接详细信息以匹配您自己的!

    用户注册表。

    在用户登录之前,他或她需要使用注册表单注册我们的网站。如果注册成功,我们将在用户表中插入一个新的用户帐户。

    1. //register.php
    2. /**
    3. * Start the session.
    4. */
    5. session_start();
    6. /**
    7. * Include our MySQL connection.
    8. */
    9. require 'connect.php';
    10. //If the POST var "register" exists (our submit button), then we can
    11. //assume that the user has submitted the registration form.
    12. if(isset($_POST['register'])){
    13. //Retrieve the field values from our registration form.
    14. $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
    15. $pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
    16. //TO ADD: Error checking (username characters, password length, etc).
    17. //Basically, you will need to add your own error checking BEFORE
    18. //the prepared statement is built and executed.
    19. //Now, we need to check if the supplied username already exists.
    20. //Construct the SQL statement and prepare it.
    21. $sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
    22. $stmt = $pdo->prepare($sql);
    23. //Bind the provided username to our prepared statement.
    24. $stmt->bindValue(':username', $username);
    25. //Execute.
    26. $stmt->execute();
    27. //Fetch the row.
    28. $row = $stmt->fetch(PDO::FETCH_ASSOC);
    29. //If the provided username already exists - display error.
    30. //TO ADD - Your own method of handling this error. For example purposes,
    31. //I'm just going to kill the script completely, as error handling is outside
    32. //the scope of this tutorial.
    33. if($row['num'] > 0){
    34. die('That username already exists!');
    35. }
    36. //Hash the password as we do NOT want to store our passwords in plain text.
    37. $passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
    38. //Prepare our INSERT statement.
    39. //Remember: We are inserting a new row into our users table.
    40. $sql = "INSERT INTO users (username, password) VALUES (:username, :password)";
    41. $stmt = $pdo->prepare($sql);
    42. //Bind our variables.
    43. $stmt->bindValue(':username', $username);
    44. $stmt->bindValue(':password', $passwordHash);
    45. //Execute the statement and insert the new account.
    46. $result = $stmt->execute();
    47. //If the signup process is successful.
    48. if($result){
    49. //What you do here is up to you!
    50. echo 'Thank you for registering with our website.';
    51. }
    52. }
    53. ?>
    54. Register
    55. Register



    需要注意的几点:

    • 我们正在使用一种名为 BCRYPT 的受人尊敬的密码散列算法。其他登录教程错误地推广了 md5 和 sha1 等哈希算法。md5 和 sha1 的问题在于它们“太快了”,这基本上意味着密码破解者可以更快地“破解”它们。
    • 您需要在此注册表单中添加您自己的错误检查(用户名长度、允许的字符类型等)。您还需要实现自己的处理用户错误的方法,因为上面的代码在这方面非常基础。有关此主题的进一步帮助,请务必查看我的关于在 PHP 中处理表单错误的教程。
    • 如果上面的插入代码对您来说完全陌生,那么您可能应该查看我关于使用 PDO 插入的文章

    用户使用 PHP 登录。

    使用 PHP 和 PDO 对象登录网站的基本示例:

    1. //login.php
    2. /**
    3. * Start the session.
    4. */
    5. session_start();
    6. /**
    7. * Include our MySQL connection.
    8. */
    9. require 'connect.php';
    10. //If the POST var "login" exists (our submit button), then we can
    11. //assume that the user has submitted the login form.
    12. if(isset($_POST['login'])){
    13. //Retrieve the field values from our login form.
    14. $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
    15. $passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null;
    16. //Retrieve the user account information for the given username.
    17. $sql = "SELECT id, username, password FROM users WHERE username = :username";
    18. $stmt = $pdo->prepare($sql);
    19. //Bind value.
    20. $stmt->bindValue(':username', $username);
    21. //Execute.
    22. $stmt->execute();
    23. //Fetch row.
    24. $user = $stmt->fetch(PDO::FETCH_ASSOC);
    25. //If $row is FALSE.
    26. if($user === false){
    27. //Could not find a user with that username!
    28. //PS: You might want to handle this error in a more user-friendly manner!
    29. die('Incorrect username / password combination!');
    30. } else{
    31. //User account found. Check to see if the given password matches the
    32. //password hash that we stored in our users table.
    33. //Compare the passwords.
    34. $validPassword = password_verify($passwordAttempt, $user['password']);
    35. //If $validPassword is TRUE, the login has been successful.
    36. if($validPassword){
    37. //Provide the user with a login session.
    38. $_SESSION['user_id'] = $user['id'];
    39. $_SESSION['logged_in'] = time();
    40. //Redirect to our protected page, which we called home.php
    41. header('Location: home.php');
    42. exit;
    43. } else{
    44. //$validPassword was FALSE. Passwords do not match.
    45. die('Incorrect username / password combination!');
    46. }
    47. }
    48. }
    49. ?>
    50. Login
    51. Login



    逐步解释上面的代码:

    1. 我们使用函数 session_start 启动会话。这个函数必须在每一页上调用。
    2. 我们需要我们的 connect.php 文件,它连接到 MySQL 并实例化 PDO 对象。
    3. 如果 POST 变量“login”存在,我们假设用户正在尝试登录我们的网站。
    4. 我们从登录表单中获取字段值。
    5. 使用我们提供的用户名,我们尝试从 MySQL 表中检索相关用户。我们通过使用准备好的 SELECT 语句来做到这一点。
    6. 如果存在具有该用户名的用户,我们将使用函数 password_verify 比较两个密码(这会为您处理哈希比较)。
    7. 如果密码哈希匹配,我们为用户提供登录会话。我们通过创建两个名为“user_id”和“logged_in”的会话变量来做到这一点。
    8. 然后我们将用户重定向到 home.php,这是我们的登录保护页面。

    注意:您需要实现自己的方式来处理用户错误。在本教程中,我使用的是 die 语句,这有点令人讨厌。

    受保护的页面。

    我们的受保护页面称为 home.php。我保持简单:

    1. //home.php
    2. /**
    3. * Start the session.
    4. */
    5. session_start();
    6. /**
    7. * Check if the user is logged in.
    8. */
    9. if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){
    10. //User not logged in. Redirect them back to the login.php page.
    11. header('Location: login.php');
    12. exit;
    13. }
    14. /**
    15. * Print out something that only logged in users can see.
    16. */
    17. echo 'Congratulations! You are logged in!';

    一步步:

    • 我使用 session_start 开始会话。这很重要,因为如果没有有效的用户会话,我们的登录系统将无法工作。
    • 我们检查用户是否具有所需的会话变量(用户 ID 和登录时间戳)。如果用户没有这些会话变量中的任何一个,我们只需将它们重定向回 l​​ogin.php 页面。显然,您可以自定义它以满足您自己的需求。
    • 我们打印出一条测试消息,只是为了表明登录系统按预期运行。

    如果您不熟悉这一切,那么您可能应该下载下面的代码示例并在您的开发/本地机器上实现登录系统。确保您阅读了代码中包含的注释!如果您有任何问题或建议,请务必在下面发表评论!

  • 相关阅读:
    python Matplotlib Tkinter-->tab切换3
    【Python脚本进阶】1.3、第一个脚本:UNIX口令破解机
    【视频图像篇】FastStone Capture屏幕直尺功能设置
    React 中ref 的使用(类组件和函数组件)以及forwardRef 与 useImperativeHandle 详解
    传统算法与神经网络算法,神经网络算法有什么用
    1326_ADC模块以及功能参数初步
    并查集路径压缩
    Prometheus集成consul[被监控对象开启basic认证]
    No suitable driver found for jdbc:mysql://localhost:3306/BookManagement
    Web服务器实现|基于阻塞队列线程池的Http服务器|线程控制|Http协议
  • 原文地址:https://blog.csdn.net/allway2/article/details/126674946