全部
常见问题
产品动态
精选推荐

【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

<?php
session_start();
 
// Define the valid credentials
define('VALID_USERNAME', 'myusername');
define('VALID_PASSWORD', 'mypassword');
 
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the username and password from the form
    $username = $_POST['username'];
    $password = $_POST['password'];
 
    // Check if the credentials are valid
    if ($username === VALID_USERNAME && $password === VALID_PASSWORD) {
        // If the credentials are valid, start a session and redirect to the protected area
        $_SESSION['loggedin'] = true;
        header('Location: protected.php');
        exit;
    } else {
        // If the credentials are not valid, display an error message
        $error = 'Invalid username or password.';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <?php if (isset($error)) { ?>
        <p><?php echo $error; ?></p>
    <?php } ?>
    <form action="login.php" method="post">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required>
        <br>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required>
        <br>
        <button type="submit">Login</button>
    </form>
</body>
</html>

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

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

<?php
ob_start(); // start output buffering
session_start();
 
// If the user is already logged in, redirect to the protected page
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
  header('Location: lsfile.php');
  exit;
}
 
// Check if the user submitted the login form
if (isset($_POST['username']) && isset($_POST['password'])) {
  // Verify the username and password (replace with your own verification code)
  if ($_POST['username'] === 'example' && $_POST['password'] === 'password') {
    // Authentication successful, set session variables
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $_POST['username'];
 
    // Redirect to the protected page
    header('Location: lsfile.php');
    exit;
  } else {
    // Authentication failed, display error message
    $error = 'Incorrect username or password';
  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
  <style>
    body {
      background-color: #f2f2f2;
    }
 
    #login-form {
      max-width: 400px;
      margin: 0 auto;
      background-color: #fff;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    }
 
    h1 {
      text-align: center;
      margin-bottom: 20px;
    }
 
    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }
 
    input[type="text"],
    input[type="password"] {
      width: 100%;
      padding: 10px;
      border-radius: 3px;
      border: 1px solid #ccc;
      margin-bottom: 20px;
    }
 
    button {
      background-color: #4CAF50;
      color: #fff;
      padding: 10px 20px;
      border: none;
      border-radius: 3px;
      cursor: pointer;
    }
 
    button:hover {
      background-color: #45a049;
    }
 
    .error-message {
      color: #f00;
      font-weight: bold;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div id="login-form">
    <h1>Login</h1>
    <?php if (isset($error)) { ?>
      <p class="error-message"><?php echo $error; ?></p>
    <?php } ?>
    <form method="post" action="login.php">
      <label for="username">Username:</label>
      <input type="text" id="username" name="username">
      <label for="password">Password:</label>
      <input type="password" id="password" name="password">
      <button type="submit">Log in</button>
    </form>
  </div>
</body>
</html>
<?php
ob_end_flush(); // flush output buffer
?>

上面代码中首先使用 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 中使用会话检查用户是否已登录,以及如何保护需要身份验证的页面:

<?php
session_start();
 
// Check if the user is logged in
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    // If the user is not logged in, redirect to the login page
    header('Location: login.php');
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Protected Page</title>
</head>
<body>
    <h1>Protected Page</h1>
    <p>This page is only accessible to logged-in users.</p>
    <p><a href="logout.php">Logout</a></p>
</body>
</html>

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

下面是另外一个示例

<?php
session_start();
 
// If the user is not logged in, redirect to the login page
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
  header('Location: login.php');
  exit;
}
 
// If the user clicked the logout link, log them out and redirect to the login page
if (isset($_GET['logout'])) {
  session_destroy(); // destroy all session data
  header('Location: login.php');
  exit;
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Protected Page</title>
  <style>
    /* Add some basic styling */
    body {
      font-family: Arial, sans-serif;
      text-align: center;
    }
    
    h1 {
      font-size: 36px;
      margin-top: 50px;
    }
    
    p {
      font-size: 18px;
      margin-top: 20px;
      margin-bottom: 20px;
    }
    
    a {
      font-size: 18px;
      color: blue;
    }
  </style>
</head>
<body>
  <header>
    <h1>Welcome to the Protected Page</h1>
  </header>
  <main>
    <p>You have successfully logged in.</p>
    <p><a href="protected.php?logout=true">Logout</a></p>
  </main>
  <footer>
    <p>Copyright © 2023 Your Company Name</p>
  </footer>
</body>
</html>

三. 注销脚本

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

<?php
session_start();
 
// Unset all of the session variables
$_SESSION = array();
 
// Destroy the session
session_destroy();
 
// Redirect to the login page
header('Location: login.php');
exit;
?>

这个代码文件首先启动会话,然后通过将 $_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命令来检查和更改目录的权限,例如:

ls -ld /var/lib/php/session
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服务器以确保更改生效:

systemctl restart php-fpm
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和哈希函数来加密用户的敏感数据。同时,它还演示了如何使用会话来控制用户的访问权限。

<?php
session_start();
 
// If the user is not logged in, redirect to the login page
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
  header('Location: login.php');
  exit;
}
 
// If the user clicked the logout link, log them out and redirect to the login page
if (isset($_GET['logout'])) {
  session_destroy(); // destroy all session data
  header('Location: login.php');
  exit;
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>哈希函数转换</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f2f2f2;
    }
    h1 {
      text-align: center;
      margin-top: 50px;
    }
    form {
      width: 400px;
      margin: 50px auto;
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0px 0px 10px rgba(0,0,0,0.2);
    }
    input[type="text"], input[type="password"] {
      width: 100%;
      padding: 10px;
      border: none;
      border-radius: 5px;
      margin-bottom: 20px;
      box-sizing: border-box;
    }
    input[type="submit"] {
      background-color: #4CAF50;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    input[type="submit"]:hover {
      background-color: #3e8e41;
    }
    .hash-result {
      width: 660px;
      margin: 50px auto;
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0px 0px 10px rgba(0,0,0,0.2);
      text-align: center;
    }
  </style>
</head>
<body>
  <h1>使用哈希函数转换字符串</h1>
  <?php
  if (isset($_POST['submit'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $username_hash = hash('sha256', $username);
    $password_hash = hash('sha256', $password);
    echo '<div class="hash-result">';
    echo '<p>用户名的哈希值为:' . $username_hash . '</p>';
    echo '<p>密码的哈希值为:' . $password_hash . '</p>';
    echo '</div>';
  } else {
    echo '<form method="post">';
    echo '<label for="username">用户名:</label>';
    echo '<input type="text" id="username" name="username" required>';
    echo '<label for="password">密码:</label>';
    echo '<input type="password" id="password" name="password" required>';
    echo '<input type="submit" name="submit" value="转换">';
    echo '</form>';
  }
  ?>
</body>
</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()函数刷新输出缓冲区。

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

<?php
ob_start(); // start output buffering
session_start();
 
// Store the hashed username and password
$hashed_username = '04f8996da763b7a969b1028ee3007569eaf3a635486ddab211d512c85b9df8fb';
$hashed_password = '98c1eb4ee93476743763878fcb96a25fbc9a175074d64004779ecb5242f645e6';
 
// If the user is already logged in, redirect to the protected page
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
  header('Location: lsfile.php');
  exit;
}
 
// Check if the user submitted the login form
if (isset($_POST['username']) && isset($_POST['password'])) {
  // Verify the username and password (replace with your own verification code)
  $submitted_username_hash = hash('sha256', $_POST['username']);
  $submitted_password_hash = hash('sha256', $_POST['password']);
 
  // Compare the submitted values with the stored hashes
  if (hash_equals($hashed_username, $submitted_username_hash) && hash_equals($hashed_password, $submitted_password_hash)) {
    // Authentication successful, set session variables
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $_POST['username'];
 
    // Redirect to the protected page
    header('Location: lsfile.php');
    exit;
  } else {
    // Authentication failed, display error message
    $error = 'Incorrect username or password';
  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
  <style>
    body {
      background-color: #f2f2f2;
    }
 
    #login-form {
      max-width: 400px;
      margin: 0 auto;
      background-color: #fff;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    }
 
    h1 {
      text-align: center;
      margin-bottom: 20px;
    }
 
    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }
 
    input[type="text"],
    input[type="password"] {
      width: 100%;
      padding: 10px;
      border-radius: 3px;
      border: 1px solid #ccc;
      margin-bottom: 20px;
    }
 
    button {
      background-color: #4CAF50;
      color: #fff;
      padding: 10px 20px;
      border: none;
      border-radius: 3px;
      cursor: pointer;
    }
 
    button:hover {
      background-color: #45a049;
    }
 
    .error-message {
      color: #f00;
      font-weight: bold;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div id="login-form">
    <h1>Login</h1>
    <?php if (isset($error)) { ?>
      <p class="error-message"><?php echo $error; ?></p>
    <?php } ?>
    <form method="post" action="login.php">
      <label for="username">Username:</label>
      <input type="text" id="username" name="username">
      <label for="password">Password:</label>
      <input type="password" id="password" name="password">
      <button type="submit">Log in</button>
    </form>
  </div>
</body>
</html>
<?php
ob_end_flush(); // flush output buffer
?>

总结

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

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

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

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

请登录后查看

CRMEB-慕白寒窗雪 最后编辑于2023-12-22 10:59:02

快捷回复
回复({{post_count}}) {{!is_user ? '我的回复' :'全部回复'}}
回复从新到旧

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}}

作者 管理员 企业

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest==1? '取消推荐': '推荐'}}
{{item.floor}}#
{{item.user_info.title}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
{{item.like_count}}
{{item.showReply ? '取消回复' : '回复'}}
删除
回复
回复

{{itemc.user_info.nickname}}

{{itemc.user_name}}

作者 管理员 企业

回复 {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}   {{itemc.ip_address}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回复' : '回复'}}
删除
回复
回复
查看更多
回复
回复
1006
{{like_count}}
{{collect_count}}
添加回复 ({{post_count}})

相关推荐

CRMEB-慕白寒窗雪 作者
社区运营专员---高冷のBoy | 呆萌のGirl

回答

2221

发布

1777

经验

45160

快速安全登录

使用微信扫码登录
{{item.label}} {{item.label}} {{item.label}} 板块推荐 常见问题 产品动态 精选推荐 首页头条 首页动态 首页推荐
加精
取 消 确 定
回复
回复
问题:
问题自动获取的帖子内容,不准确时需要手动修改. [获取答案]
答案:
提交
bug 需求 取 消 确 定

微信登录/注册

切换手机号登录

{{ bind_phone ? '绑定手机' : '手机登录'}}

{{codeText}}
切换微信登录/注册
暂不绑定
CRMEB客服

CRMEB咨询热线 咨询热线

400-8888-794

微信扫码咨询

CRMEB开源商城下载 开源下载 CRMEB官方论坛 帮助文档
返回顶部 返回顶部
CRMEB客服