How can PHP be used to display user information after login?

To display user information after logging in PHP, first, the following steps are required:

  1. Create a login page with input fields for username and password, as well as a login button.
  2. After the form on the login page is submitted, the PHP code will receive the form data and proceed with validation. It is possible to verify if the username and password match the data in the database.
  3. If the verification is successful, user information can be stored in the session for use on other pages. For example, the username, user ID, and other information can be stored in the session.
  4. On other pages where user information needs to be displayed, the user information can be retrieved through a session and displayed as needed.

Here is a simple example code:

Login page (login.php):

<!DOCTYPE html>
<html>
<head>
    <title>登录页面</title>
</head>
<body>
    <h2>登录</h2>
    <form action="login_process.php" method="post">
        <label for="username">用户名:</label>
        <input type="text" name="username" id="username" required><br>
        <label for="password">密码:</label>
        <input type="password" name="password" id="password" required><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

Login processing page (login_process.php):

<?php
session_start();

// 假设数据库中有一个用户表,包含用户名和密码字段
$users = [
    ['username' => 'user1', 'password' => 'pass1'],
    ['username' => 'user2', 'password' => 'pass2'],
    ['username' => 'user3', 'password' => 'pass3']
];

$username = $_POST['username'];
$password = $_POST['password'];

// 验证用户名和密码是否匹配
$loggedIn = false;
foreach ($users as $user) {
    if ($user['username'] === $username && $user['password'] === $password) {
        $loggedIn = true;
        break;
    }
}

if ($loggedIn) {
    // 登录成功,将用户信息存储在session中
    $_SESSION['username'] = $username;
    $_SESSION['userId'] = 123; // 假设用户ID为123

    header('Location: profile.php'); // 重定向到用户信息页面
} else {
    // 登录失败,返回登录页面
    header('Location: login.php');
}
?>

Profile Page (profile.php):

<?php
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

// 获取用户信息
$username = $_SESSION['username'];
$userId = $_SESSION['userId'];

// 展示用户信息
echo "用户名:$username<br>";
echo "用户ID:$userId";
?>

In this example, when a user enters their username and password on the login page, the form is submitted to the login processing page (login_process.php). On the login processing page, the username and password are verified to match the data in the database. If the verification is successful, the user information is stored in a session and redirected to the user information page (profile.php). On the user information page, the user information is retrieved from the session and displayed. If the user is not logged in or there is no user information stored in the session, they will be redirected back to the login page.

bannerAds