如何记录登录条目和会话状态?我一直在寻找源代码和想法,但有些我听不懂。我想通过PHP询问一个简单的代码。我有一个代码可以登录用户,但不需要MySql数据库,我想知道如何记录登录条目和会话状态连接我的PHP登录代码。或者,如果您有其他需要MySql数据库的选项代码。
这是代码:
"CONFIG.PHP"
<?php
$user = "admin";
$pass = "password";
?>
"INDEX.PHP"
<?php
include("config.php");
// Check form if is submited
if(isSet($_POST['trimite'])) {
// Check if user is equal with username and password from config.php
if($_POST['user'] != $user || $_POST['pass'] != $pass) {
echo "Sorry, your data is invalid";
} else {
// Open the session for store user logged
session_start();
// Setting the session
$_SESSION['logat'] = "da";
// Redirecting user to admin page if is logged
Header('Location: admin.php');
}
} else {
// Form
echo '<form action="" method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" name="trimite">
</form>';
}
?>
"ADMIN.PHP"
<?php
include("config.php");
// Start session
session_start();
// Check if user is logged and existing session
if(isset($_SESSION['logat'])) {
// Content for user logged
echo "Welcome ".$user." :) - <a href='logout.php'>Logout</a>";
} else {
// Redirecting to login page
Header("Location: ./");
}
?>
始终将session_start()
作为<?php
之后的第一个语句
即使用户没有登录,也可以运行session_start()。session_start()
应该是第一条语句。
请注意,header()
命令需要小写的h
(而不是Header
——这是错误的)。
index.php
<?php
session_start();
include("config.php");
// Check form if is submited
if( isSet($_POST['user']) ) {
// Check if user is equal with username and password from config.php
if($_POST['user'] != $user || $_POST['pass'] != $pass) {
echo "Sorry, your data is invalid";
} else {
// Open the session for store user logged
// Setting the session
$_SESSION['logat'] = "da";
$_SESSION['username'] = $_POST['user'];
// Redirecting user to admin page if is logged
header('Location: admin.php');
}
} else {
// Form
$out = '
<form action="" method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" name="trimite">
</form>
';
echo $out;
}
?>
admin.php-以下是如何引用/使用用户名会话变量:
<?php
// Start session
session_start();
include("config.php");
// Check if user is logged and existing session
if(isset($_SESSION['logat'])) {
// Content for user logged
echo "Welcome ".$_SESSION['username']." :) - <a href='logout.php'>Logout</a>";
} else {
// Redirecting to login page
header("Location: ./");
}
?>
请注意,只有在尚未向DOM发送数据的情况下才能使用header
。有时这种情况很难预防。这里有一个HTML标签,可以让你重定向到另一个页面:
<meta http-equiv="refresh" content="0;url=http://example.com">
数字零(在url=
之前)表示重定向页面之前等待的秒数。