下面描述的当前代码不起作用。我想在会话中存储用户名并将其显示在主页中。这是我用来存储和显示用户名的代码。当用户名正确时,这将指向主页。
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" name="submit" class="btn btn-success" value="Login" />
<?php
session_start();
$error='';
if (isset($_POST['submit']))
{
$username = $_SESSION['username'];
$username = $_SESSION['login_user'];
if (empty($_POST['username']) || empty($_POST['password']))
{
echo "<script type='text/javascript'>alert('Username or Password is invalid')</script>";
}
else
{
$username=$_POST['username'];
$password=$_POST['password'];
$con = mysqli_connect("mysql.site","username","password","database");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$query = mysqli_query($con,"select * from userprofile where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1)
{
$_SESSION['username']=$username;
$_SESSION['login_user']=$username;
if (isset($_POST['rememberme'])) {
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', md5($_POST['password']), time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false, '/account', 'www.example.com');
setcookie('password', md5($_POST['password']), false, '/account', 'www.example.com');
}
header('Location: home.php');
}
else
{
echo "<script type='text/javascript'>alert('Invalid Username & Password')</script>";
header('Location: home.php');
}
mysqli_close($con);
}
}
?>
当会话为空时,此代码将导航到login(index.php)页面。
home.php
<?php
if (!isset($_SESSION)) {
session_start();
}
if(!$_SESSION['username']) {
header('Location: index.php');
exit;
}
?>
此代码现在无效,但当我删除此代码时,它正在运行。
if(!$_SESSION['username']) {
header('Location: index.php');
exit;
}
答案 0 :(得分:2)
尝试这样的操作,删除第一个if
条件,然后更改第二个if
条件
<?php
session_start();
if(!isset($_SESSION['username'])) {
header('Location: index.php');
exit;
}
?>