当前位置:   article > 正文

【PHP进阶教程】手把手教你实现用户登录验证(附实战代码)_php登录

php登录

1. 登陆脚本

2. 受保护的网页示例

3. 注销脚本

4. 注意事项

5. Hash函数字符串转换

6. php登陆脚本(哈希值验证)

076cb202312221045235226.png

可以使用 PHP 创建登录脚本。PHP 提供了用于处理用户身份验证和会话的内置函数和功能,这是登录系统的基本组件。这些功能允许您安全地存储和验证用户凭据,并在用户与您的网站或应用程序的交互过程中维护用户会话。还有许多 PHP 框架和库可用,提供预构建的登录系统功能,使您更容易在项目中实现登录功能。

问:如何使用php限制未注册的人访问存储在云服务器中的html ?

为了限制只有注册用户才能访问存储在云服务器上的HTML文件,可以使用PHP创建一个登录系统来限制对这些文件的访问。以下是所涉及步骤的总体概述:

1.创建一个允许用户输入用户名和密码的登录表单。

2.使用PHP处理登录表单,并根据数据库或其他存储验证用户的凭据。

3.如果登录成功,则创建一个会话来存储用户信息,并设置一个标志来表示用户已登录。

4.对于希望限制访问的每个HTML文件,在文件的顶部包含PHP代码,用于检查用户是否已登录。如果用户未登录,请将其重定向到登录页面。

5.当用户注销时,销毁会话并清除登录标志。

一. 登陆脚本

这里需要注意程序是否具有对保存session目录的读取和写入权限。

login.php

  1. <?php
  2. session_start();
  3. // Define the valid credentials
  4. define('VALID_USERNAME', 'myusername');
  5. define('VALID_PASSWORD', 'mypassword');
  6. // Check if the form was submitted
  7. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  8. // Get the username and password from the form
  9. $username = $_POST['username'];
  10. $password = $_POST['password'];
  11. // Check if the credentials are valid
  12. if ($username === VALID_USERNAME && $password === VALID_PASSWORD) {
  13. // If the credentials are valid, start a session and redirect to the protected area
  14. $_SESSION['loggedin'] = true;
  15. header('Location: protected.php');
  16. exit;
  17. } else {
  18. // If the credentials are not valid, display an error message
  19. $error = 'Invalid username or password.';
  20. }
  21. }
  22. ?>
  23. <!DOCTYPE html>
  24. <html>
  25. <head>
  26. <title>Login</title>
  27. </head>
  28. <body>
  29. <h1>Login</h1>
  30. <?php if (isset($error)) { ?>
  31. <p><?php echo $error; ?></p>
  32. <?php } ?>
  33. <form action="login.php" method="post">
  34. <label for="username">Username:</label>
  35. <input type="text" name="username" id="username" required>
  36. <br>
  37. <label for="password">Password:</label>
  38. <input type="password" name="password" id="password" required>
  39. <br>
  40. <button type="submit">Login</button>
  41. </form>
  42. </body>
  43. </html>

这是一个使用PHP编写的简单登录系统的示例代码,它采用了常量来定义有效的用户名和密码。当用户提交登录表单时,脚本会检查输入的凭据是否与有效值匹配。如果凭据正确,脚本会设置一个会话变量以表示用户已登录,并重定向到受保护的区域。如果凭据不正确,脚本会显示一个错误消息。请注意,这只是一个简单的示例,不适用于生产环境。在真实的应用中,您需要安全地存储用户凭据,并保护免受常见的安全漏洞,如SQL注入和跨站脚本攻击(XSS)。

下面是另外一个UI经过优化的示例。

  1. <?php
  2. ob_start(); // start output buffering
  3. session_start();
  4. // If the user is already logged in, redirect to the protected page
  5. if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
  6. header('Location: lsfile.php');
  7. exit;
  8. }
  9. // Check if the user submitted the login form
  10. if (isset($_POST['username']) && isset($_POST['password'])) {
  11. // Verify the username and password (replace with your own verification code)
  12. if ($_POST['username'] === 'example' && $_POST['password'] === 'password') {
  13. // Authentication successful, set session variables
  14. $_SESSION['loggedin'] = true;
  15. $_SESSION['username'] = $_POST['username'];
  16. // Redirect to the protected page
  17. header('Location: lsfile.php');
  18. exit;
  19. } else {
  20. // Authentication failed, display error message
  21. $error = 'Incorrect username or password';
  22. }
  23. }
  24. ?>
  25. <!DOCTYPE html>
  26. <html>
  27. <head>
  28. <title>Login</title>
  29. <style>
  30. body {
  31. background-color: #f2f2f2;
  32. }
  33. #login-form {
  34. max-width: 400px;
  35. margin: 0 auto;
  36. background-color: #fff;
  37. padding: 20px;
  38. border-radius: 5px;
  39. box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  40. }
  41. h1 {
  42. text-align: center;
  43. margin-bottom: 20px;
  44. }
  45. label {
  46. display: block;
  47. margin-bottom: 5px;
  48. font-weight: bold;
  49. }
  50. input[type="text"],
  51. input[type="password"] {
  52. width: 100%;
  53. padding: 10px;
  54. border-radius: 3px;
  55. border: 1px solid #ccc;
  56. margin-bottom: 20px;
  57. }
  58. button {
  59. background-color: #4CAF50;
  60. color: #fff;
  61. padding: 10px 20px;
  62. border: none;
  63. border-radius: 3px;
  64. cursor: pointer;
  65. }
  66. button:hover {
  67. background-color: #45a049;
  68. }
  69. .error-message {
  70. color: #f00;
  71. font-weight: bold;
  72. margin-bottom: 10px;
  73. }
  74. </style>
  75. </head>
  76. <body>
  77. <div id="login-form">
  78. <h1>Login</h1>
  79. <?php if (isset($error)) { ?>
  80. <p class="error-message"><?php echo $error; ?></p>
  81. <?php } ?>
  82. <form method="post" action="login.php">
  83. <label for="username">Username:</label>
  84. <input type="text" id="username" name="username">
  85. <label for="password">Password:</label>
  86. <input type="password" id="password" name="password">
  87. <button type="submit">Log in</button>
  88. </form>
  89. </div>
  90. </body>
  91. </html>
  92. <?php
  93. ob_end_flush(); // flush output buffer
  94. ?>

上面代码中首先使用 ob_start() 函数开启输出缓存,然后使用 session_start() 函数开启会话,如果用户已经登录,就将页面重定向到受保护的页面 lsfile.php,如果用户还没有登录,就显示登录表单。

如果用户提交了登录表单,就进行身份验证。在这里,使用了简单的用户名和密码验证,如果验证成功,就将会话变量 $_SESSION['loggedin'] 和 $_SESSION['username'] 设置为 true 和用户名,然后将页面重定向到受保护的页面。如果验证失败,就显示错误消息 $error。

HTML 代码包含一个标题和一个表单,表单包含用户名和密码输入框以及一个提交按钮。在表单提交时,将表单数据发送到相同的脚本 login.php 中进行处理。

这个登录页面还包含一些 CSS 样式,用于设置页面布局和样式。ob_end_flush() 函数用于刷新输出缓存并输出内容。

如果别人想要破解这个登录页面,他们可能会使用以下方法:

1.字典攻击:攻击者可能会使用常见的用户名和密码组合构建一个字典文件,并尝试使用字典文件中的用户名和密码来尝试登录。

2.暴力攻击:攻击者可能会使用程序来生成随机的用户名和密码,并尝试使用这些凭据来尝试登录。暴力攻击需要大量的计算资源和时间。

3.SQL 注入攻击:如果输入的用户名和密码没有正确地过滤和验证,攻击者可能会尝试在 SQL 查询中注入恶意代码,从而绕过身份验证并访问受保护的页面。

4.XSS 攻击:如果登录页面没有对用户输入的内容进行适当的过滤和转义,攻击者可能会在页面上注入恶意脚本,从而获取用户的登录凭据或执行其他恶意操作。

5.社会工程学攻击:攻击者可能会尝试通过欺骗用户来获取其登录凭据,例如通过钓鱼邮件或伪装成真实的登录页面。

为了确保登录页面的安全性,应该采取以下措施:

1.使用强密码策略:要求用户使用包含大小写字母、数字和符号的复杂密码,并限制密码长度和重复使用密码。

2.实施验证码:为登录页面添加验证码,以确保登录请求来自真实用户而不是自动化程序。

3.使用 HTTPS:使用 HTTPS 协议来加密登录页面和用户凭据,以防止中间人攻击和数据泄露。

4.进行输入验证:对输入的用户名和密码进行验证和过滤,以防止 SQL 注入和 XSS 攻击。

5.实施多重身份验证:使用多个身份验证因素,例如密码和短信验证码,来提高安全性。

6.更新和监测登录活动:记录和监控用户的登录活动,及时发现和响应异常登录行为。

二. 受保护的网页示例

下面是一个示例代码,演示如何在 PHP 中使用会话检查用户是否已登录,以及如何保护需要身份验证的页面:

  1. <?php
  2. session_start();
  3. // Check if the user is logged in
  4. if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
  5. // If the user is not logged in, redirect to the login page
  6. header('Location: login.php');
  7. exit;
  8. }
  9. ?>
  10. <!DOCTYPE html>
  11. <html>
  12. <head>
  13. <title>Protected Page</title>
  14. </head>
  15. <body>
  16. <h1>Protected Page</h1>
  17. <p>This page is only accessible to logged-in users.</p>
  18. <p><a href="logout.php">Logout</a></p>
  19. </body>
  20. </html>

这个代码文件首先启动会话,然后检查用户是否已经登录。如果用户没有登录,脚本会将浏览器重定向到登录页面。否则,脚本会显示一个受保护的页面,只有登录用户才能访问。页面上还包括一个链接,可以让用户注销并结束会话。

下面是另外一个示例

  1. <?php
  2. session_start();
  3. // If the user is not logged in, redirect to the login page
  4. if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
  5. header('Location: login.php');
  6. exit;
  7. }
  8. // If the user clicked the logout link, log them out and redirect to the login page
  9. if (isset($_GET['logout'])) {
  10. session_destroy(); // destroy all session data
  11. header('Location: login.php');
  12. exit;
  13. }
  14. ?>
  15. <!DOCTYPE html>
  16. <html>
  17. <head>
  18. <title>Protected Page</title>
  19. <style>
  20. /* Add some basic styling */
  21. body {
  22. font-family: Arial, sans-serif;
  23. text-align: center;
  24. }
  25. h1 {
  26. font-size: 36px;
  27. margin-top: 50px;
  28. }
  29. p {
  30. font-size: 18px;
  31. margin-top: 20px;
  32. margin-bottom: 20px;
  33. }
  34. a {
  35. font-size: 18px;
  36. color: blue;
  37. }
  38. </style>
  39. </head>
  40. <body>
  41. <header>
  42. <h1>Welcome to the Protected Page</h1>
  43. </header>
  44. <main>
  45. <p>You have successfully logged in.</p>
  46. <p><a href="protected.php?logout=true">Logout</a></p>
  47. </main>
  48. <footer>
  49. <p>Copyright © 2023 Your Company Name</p>
  50. </footer>
  51. </body>
  52. </html>
三. 注销脚本

这里是一个简单的 logout.php 示例代码,用于在 PHP 中结束会话并注销用户:

  1. <?php
  2. session_start();
  3. // Unset all of the session variables
  4. $_SESSION = array();
  5. // Destroy the session
  6. session_destroy();
  7. // Redirect to the login page
  8. header('Location: login.php');
  9. exit;
  10. ?>

这个代码文件首先启动会话,然后通过将 $_SESSION 数组设置为空数组来清除所有会话变量。然后,通过调用 session_destroy() 函数来销毁会话,并确保删除会话 cookie。最后,脚本将浏览器重定向到登录页面。

注意,在销毁会话之前,您可能还需要进行其他一些清理操作,如清除任何持久登录 cookie 或删除会话数据库中的条目。

四. 注意事项(session常见报错)

报错1:会话存储目录/var/lib/php/session属组为apache,实际应该是nginx

php报错,如何解决,2023/04/11 12:50:26 [error] 1512#1512: *22 FastCGI sent in stderr: "PHP message: PHP Warning: Unknown: open(/var/lib/php/session/sess_espb5d8tqnhufh7djlledte2g5, O_RDWR) failed: Permission denied (13) in Unknown on line 0

PHP message: PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0" while reading upstream, client: 28.247.135.8, server: 10.200.215.127, request: "POST /login.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "10.200.215.127", referrer: "Login"

分析:

这个错误信息是由于PHP应用程序无法写入会话数据导致的。这通常是由于会话存储目录的权限设置不正确或者会话存储目录不存在引起的。要解决这个问题,您可以按照以下步骤进行操作:

确认会话存储目录是否存在,并具有足够的权限让PHP应用程序写入会话数据文件。您可以使用ls和chmod命令来检查和更改目录的权限,例如:

  1. ls -ld /var/lib/php/session
  2. chmod 733 /var/lib/php/session

检查php.ini文件中session.save_path设置是否正确,并确保它指向实际存在的目录。您可以使用以下命令查找php.ini文件:

php -i | grep 'php.ini'

然后使用nano或vim编辑器打开php.ini文件并查找session.save_path设置。

重启PHP-FPM或Web服务器以确保更改生效:

  1. systemctl restart php-fpm
  2. systemctl restart nginx

如果您仍然遇到相同的错误,请检查其他可能的问题,例如磁盘空间不足或文件系统故障等。

解决方法:

会话存储目录/var/lib/php/session的权限设置为drwxrwx---,属主为root,属组为apache。这意味着只有root用户和apache组的用户才有权限读、写、执行这个目录。

如果您的PHP应用程序运行在nginx用户下,它将无法访问会话存储目录,从而导致类似于"Permission denied"的错误。要解决这个问题,您可以考虑以下几种解决方案之一:

将nginx用户添加到apache组中,以便nginx用户可以访问会话存储目录:

usermod -a -G apache nginx

然后重新启动nginx服务:

systemctl restart nginx

更改会话存储目录的权限,以便nginx用户有权访问该目录:

chmod 777 /var/lib/php/session

请注意,这种方式会使会话存储目录变得不安全,因为任何人都可以读、写、执行该目录中的文件。因此,建议在生产环境中避免使用这种方式。

将会话存储方式更改为使用其他存储机制,例如Memcached或Redis,以避免使用文件系统存储会话数据。

您可以在php.ini文件中找到session.save_handler和session.save_path设置来更改会话存储机制。有关更多信息,请参阅PHP文档。

请注意,这种方式需要安装和配置额外的软件和服务,并可能会对性能产生影响。因此,建议在必要时使用这种方式。

五. Hash函数字符串转换

下面代码使用PHP编写的Web页面代码,主要是用于展示如何使用哈希函数来转换字符串。下面是对这段代码的分析:

1.代码开始使用session_start()函数启用会话,并且检查用户是否已经登录,如果没有则将用户重定向到登录页面。

2.如果用户已经登录,则检查URL参数logout是否存在。如果存在,表示用户点击了退出链接,将销毁当前会话并重定向到登录页面。

3.然后,代码开始构建HTML页面。在页面中,用户可以输入用户名和密码,并且通过点击“转换”按钮,将使用SHA-256哈希函数将用户名和密码转换为哈希值。

4.如果用户已经提交了表单,代码会从$_POST数组中获取提交的用户名和密码,并使用hash()函数计算它们的SHA-256哈希值。然后,它将结果显示在一个<div>元素中。

5.如果用户还没有提交表单,代码将显示一个表单,让用户输入用户名和密码。

总之,这段代码主要是用于展示如何使用PHP和哈希函数来加密用户的敏感数据。同时,它还演示了如何使用会话来控制用户的访问权限。

  1. <?php
  2. session_start();
  3. // If the user is not logged in, redirect to the login page
  4. if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
  5. header('Location: login.php');
  6. exit;
  7. }
  8. // If the user clicked the logout link, log them out and redirect to the login page
  9. if (isset($_GET['logout'])) {
  10. session_destroy(); // destroy all session data
  11. header('Location: login.php');
  12. exit;
  13. }
  14. ?>
  15. <!DOCTYPE html>
  16. <html>
  17. <head>
  18. <title>哈希函数转换</title>
  19. <style>
  20. body {
  21. font-family: Arial, sans-serif;
  22. background-color: #f2f2f2;
  23. }
  24. h1 {
  25. text-align: center;
  26. margin-top: 50px;
  27. }
  28. form {
  29. width: 400px;
  30. margin: 50px auto;
  31. background-color: #fff;
  32. padding: 20px;
  33. border-radius: 10px;
  34. box-shadow: 0px 0px 10px rgba(0,0,0,0.2);
  35. }
  36. input[type="text"], input[type="password"] {
  37. width: 100%;
  38. padding: 10px;
  39. border: none;
  40. border-radius: 5px;
  41. margin-bottom: 20px;
  42. box-sizing: border-box;
  43. }
  44. input[type="submit"] {
  45. background-color: #4CAF50;
  46. color: white;
  47. padding: 10px 20px;
  48. border: none;
  49. border-radius: 5px;
  50. cursor: pointer;
  51. }
  52. input[type="submit"]:hover {
  53. background-color: #3e8e41;
  54. }
  55. .hash-result {
  56. width: 660px;
  57. margin: 50px auto;
  58. background-color: #fff;
  59. padding: 20px;
  60. border-radius: 10px;
  61. box-shadow: 0px 0px 10px rgba(0,0,0,0.2);
  62. text-align: center;
  63. }
  64. </style>
  65. </head>
  66. <body>
  67. <h1>使用哈希函数转换字符串</h1>
  68. <?php
  69. if (isset($_POST['submit'])) {
  70. $username = $_POST['username'];
  71. $password = $_POST['password'];
  72. $username_hash = hash('sha256', $username);
  73. $password_hash = hash('sha256', $password);
  74. echo '<div class="hash-result">';
  75. echo '<p>用户名的哈希值为:' . $username_hash . '</p>';
  76. echo '<p>密码的哈希值为:' . $password_hash . '</p>';
  77. echo '</div>';
  78. } else {
  79. echo '<form method="post">';
  80. echo '<label for="username">用户名:</label>';
  81. echo '<input type="text" id="username" name="username" required>';
  82. echo '<label for="password">密码:</label>';
  83. echo '<input type="password" id="password" name="password" required>';
  84. echo '<input type="submit" name="submit" value="转换">';
  85. echo '</form>';
  86. }
  87. ?>
  88. </body>
  89. </html>
六. php登陆脚本(哈希值验证)

下面一段使用PHP编写的用户登录页面代码,主要用于验证用户的凭据并授权访问受保护的页面。下面是对这段代码的分析:

1.代码开头使用ob_start()函数启用输出缓冲区,并使用session_start()函数启用会话。

2.代码中定义了用户名和密码的哈希值,这些哈希值是预先计算的。在实际的应用程序中,这些哈希值应该存储在数据库中,并与用户输入的凭据进行比较。

3.如果用户已经登录,代码将重定向到受保护的页面lsfile.php。

4.如果用户提交了登录表单,代码将获取表单中的用户名和密码,并将其哈希。然后,代码将这些哈希值与预先计算的哈希值进行比较。如果匹配成功,代码将设置会话变量loggedin和username,并将用户重定向到受保护的页面lsfile.php。否则,代码将显示错误消息。

5.页面中包含一个表单,允许用户输入用户名和密码。如果有错误消息,代码将显示它们。

6.页面中的JavaScript代码使用了CSS样式表来格式化表单元素和页面布局。

7.最后,代码使用ob_end_flush()函数刷新输出缓冲区。

总的来说,这段代码是一个简单的用户登录页面,提供基本的用户认证功能。但是,实际的应用程序需要更多的安全性和认证功能,例如密码重置、多因素身份验证等。

  1. <?php
  2. ob_start(); // start output buffering
  3. session_start();
  4. // Store the hashed username and password
  5. $hashed_username = '04f8996da763b7a969b1028ee3007569eaf3a635486ddab211d512c85b9df8fb';
  6. $hashed_password = '98c1eb4ee93476743763878fcb96a25fbc9a175074d64004779ecb5242f645e6';
  7. // If the user is already logged in, redirect to the protected page
  8. if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
  9. header('Location: lsfile.php');
  10. exit;
  11. }
  12. // Check if the user submitted the login form
  13. if (isset($_POST['username']) && isset($_POST['password'])) {
  14. // Verify the username and password (replace with your own verification code)
  15. $submitted_username_hash = hash('sha256', $_POST['username']);
  16. $submitted_password_hash = hash('sha256', $_POST['password']);
  17. // Compare the submitted values with the stored hashes
  18. if (hash_equals($hashed_username, $submitted_username_hash) && hash_equals($hashed_password, $submitted_password_hash)) {
  19. // Authentication successful, set session variables
  20. $_SESSION['loggedin'] = true;
  21. $_SESSION['username'] = $_POST['username'];
  22. // Redirect to the protected page
  23. header('Location: lsfile.php');
  24. exit;
  25. } else {
  26. // Authentication failed, display error message
  27. $error = 'Incorrect username or password';
  28. }
  29. }
  30. ?>
  31. <!DOCTYPE html>
  32. <html>
  33. <head>
  34. <title>Login</title>
  35. <style>
  36. body {
  37. background-color: #f2f2f2;
  38. }
  39. #login-form {
  40. max-width: 400px;
  41. margin: 0 auto;
  42. background-color: #fff;
  43. padding: 20px;
  44. border-radius: 5px;
  45. box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  46. }
  47. h1 {
  48. text-align: center;
  49. margin-bottom: 20px;
  50. }
  51. label {
  52. display: block;
  53. margin-bottom: 5px;
  54. font-weight: bold;
  55. }
  56. input[type="text"],
  57. input[type="password"] {
  58. width: 100%;
  59. padding: 10px;
  60. border-radius: 3px;
  61. border: 1px solid #ccc;
  62. margin-bottom: 20px;
  63. }
  64. button {
  65. background-color: #4CAF50;
  66. color: #fff;
  67. padding: 10px 20px;
  68. border: none;
  69. border-radius: 3px;
  70. cursor: pointer;
  71. }
  72. button:hover {
  73. background-color: #45a049;
  74. }
  75. .error-message {
  76. color: #f00;
  77. font-weight: bold;
  78. margin-bottom: 10px;
  79. }
  80. </style>
  81. </head>
  82. <body>
  83. <div id="login-form">
  84. <h1>Login</h1>
  85. <?php if (isset($error)) { ?>
  86. <p class="error-message"><?php echo $error; ?></p>
  87. <?php } ?>
  88. <form method="post" action="login.php">
  89. <label for="username">Username:</label>
  90. <input type="text" id="username" name="username">
  91. <label for="password">Password:</label>
  92. <input type="password" id="password" name="password">
  93. <button type="submit">Log in</button>
  94. </form>
  95. </div>
  96. </body>
  97. </html>
  98. <?php
  99. ob_end_flush(); // flush output buffer
  100. ?>

总结

有很多编程语言和框架可以用来构建登录系统,并提供类似于PHP的功能。

一些流行的Web开发框架,如Ruby on Rails、Django(Python)和ASP.NET(C#),提供了内置的身份验证系统,使得添加用户注册、登录和注销功能变得简单。

其他编程语言,如Node.js(JavaScript)、Java和Go也可以使用各种Web开发框架和库来构建登录系统。

关键是选择一种适合您的开发技能和项目要求的语言和框架,并遵循安全和用户身份验证的最佳实践。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/751408
推荐阅读
相关标签
  

闽ICP备14008679号