In web development, page redirection after user login is a very common feature. Using PHP, we can manage the user's login status through session_start() , and then combine the header() function to realize page redirection. This article will explain how to implement this function step by step.
session_start()
session_start() is a method used in PHP to start a session. It will save user information on the server side, such as user name, user ID, etc., so as to identify the same user in multiple requests.
header()
header() is a function used by PHP to send raw HTTP header information. One of the common uses is to send a Location header, which allows the browser to jump to another page.
Need to note:
header() must be called before outputting anything, including spaces or HTML.
session_start() should also be called before any output.
Suppose we have a simple login form, and after logging in successfully, we need to jump to the user's personal homepage.
<?php
// Open session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>User login</title>
</head>
<body>
<form method="post" action="login_process.php">
username: <input type="text" name="username"><br>
password: <input type="password" name="password"><br>
<input type="submit" value="Log in">
</form>
</body>
</html>
<?php
session_start();
// 模拟的username和password
$correct_username = 'admin';
$correct_password = '123456';
// Get the submitted data
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
// 检查username和password是否正确
if ($username === $correct_username && $password === $correct_password) {
// Log in成功,set up session
$_SESSION['username'] = $username;
// Jump to user homepage
header('Location: https://m66.net/user_home.php');
exit;
} else {
// Log in失败,跳转回Log in页
header('Location: https://m66.net/login.php?error=1');
exit;
}
?>
<?php
session_start();
// 检查是否已Log in
if (!isset($_SESSION['username'])) {
// 如果没有Log in,跳转到Log in页面
header('Location: https://m66.net/login.php');
exit;
}
$username = $_SESSION['username'];
?>
<!DOCTYPE html>
<html>
<head>
<title>welcome,<?php echo htmlspecialchars($username); ?></title>
</head>
<body>
<h1>welcome回来,<?php echo htmlspecialchars($username); ?>!</h1>
<p><a href="logout.php">退出Log in</a></p>
</body>
</html>
<?php
session_start();
session_unset();
session_destroy();
// 跳转回Log in页面
header('Location: https://m66.net/login.php');
exit;
?>
Call header() and session_start() before output
As long as there is any output on the page (including HTML, spaces, line breaks, etc.), header() and session_start() will report an error. Make sure they are called at the top of the file.
Security <br> In the example code, the user name and password are written dead. In actual projects, they should be retrieved from the database and used encryption (such as password_hash() and password_verify() ).
Log out <br> Be sure to clean the session when exiting, otherwise the user status will still exist even if you jump back to the login page.