Home > Article > Backend Development > PHP process control case: implementing a user login function
Suppose there is a website that needs to implement user login function. According to the general process, the implementation method is roughly divided into the following steps:
1. Display the login interface and let the user enter the user name and password
2. Receive the user name and password entered by the user for verification
3. If the verification is passed, jump to the user's homepage, otherwise prompt the user to re-enter
The following is a simple PHP code to demonstrate how to implement this Login function:
<?php // 检查用户是否已经登录 session_start(); if (isset($_SESSION['user'])) { header('Location: user_homepage.php'); exit; } // 处理表单提交 if (isset($_POST['submit'])) { $username = $_POST['username']; $password = $_POST['password']; // 模拟用户验证 if ($username == 'admin' && $password == '123456') { // 验证通过,保存登录状态,并跳转到用户主页 $_SESSION['user'] = $username; header('Location: user_homepage.php'); exit; } else { // 验证失败,显示错误消息 $error_msg = '用户名或密码不正确,请重新输入。'; } } // 显示登录界面 ?> <!DOCTYPE html> <html> <head> <title>用户登录</title> </head> <body> <h1>用户登录</h1> <?php if (isset($error_msg)) { ?> <p style="color: red;"><?php echo $error_msg; ?></p> <?php } ?> <form method="post"> <label>用户名:</label> <input type="text" name="username" required><br> <label>密码:</label> <input type="password" name="password" required><br> <button type="submit" name="submit">登录</button> </form> </body> </html>
In the above code, first check whether the user is logged in, and if so, jump directly to the user's homepage. If the user is not logged in yet, handle form submission. If the username and password are correct, save the login status and jump to the user's homepage; otherwise, an error message is displayed, prompting the user to re-enter.
This example shows us how to use PHP’s flow control statements if, elseif, else and switch to implement the user login function.
Through different conditional judgments, different operations are performed according to different situations, thereby achieving some basic process control.
The above is the detailed content of PHP process control case: implementing a user login function. For more information, please follow other related articles on the PHP Chinese website!