我有这个登录表单.php,其中包含这部分代码(这是从索引调用的.php带有登录表单):
include("config.php");
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "" || $password == "")
{
echo "Either username or password field is empty.";
echo "<br/>";
echo "<a href='index.php'>Go back</a>";
}
else
{
$result = mysql_query("select * from users where user_username='$username' and user_password='$password'",$conn)
or die("Could not execute the select query.");
$row = mysql_fetch_assoc($result);
if(is_array($row) && !empty($row))
{
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
}
else
{
echo "Username and password do not match.";
echo "<br/>";
echo "<a href='index.php'>Go back</a>";
}
if(isset($_SESSION['valid']))
{
header("Location:index.php?");
}
}
}
但在那之后,它应该再次显示索引.php没有登录表单
index.php有以下代码在成功登录后显示用户:
<?php
if(isset($_SESSION['valid']))
{
include("config.php");
$result = mysql_query("select * from users",$conn);
echo "Welcome ".$_SESSION['valid']. "! <a href='logout.php'>Logout</a><br/>";
}
else
{
require('./loginform.php');
}
?>
使用此代码,登录表单不会显示,而是不显示任何内容。它应显示已登录的用户。我不知道我错过了什么。我是 php 的新手。请帮忙。抱歉,请假设所有文件都有会话启动。
在检查会话变量是否存在之前,您必须添加session_start()
。
<?php
session_start();
if(isset($_SESSION['valid']))
....
session_start()
创建会话或恢复当前会话。