【问题标题】:Php session is not working in my codePhp 会话在我的代码中不起作用
【发布时间】:2017-08-11 08:47:35
【问题描述】:

下面描述的当前代码不起作用。我想将用户名存储在会话中并将其显示在主页中。这是我用来存储和显示用户名的代码。当用户名正确时,这将指向主页。

<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);
    }
    }
    ?>

当会话为空时,此代码将导航到登录 (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;
    }

【问题讨论】:

  • 让我们假设您的查询工作正常,并且您从数据库中获得了所需的一切。在页面的开头声明 session_start()。将 html 代码放在 php 代码下方。它应该可以工作。

标签: php html session


【解决方案1】:

试试这样,删除第一个 if 条件,然后更改第二个 if 条件

<?php
    session_start();
    if(!isset($_SESSION['username'])) {
        header('Location: index.php');
        exit;
    }

?>

【讨论】:

  • 当我删除这些行 "if(!isset($_SESSION['username'])) { header('Location: index.php'); exit; }; from home.php从登录页面重定向到主页。
  • 当我使用上面的代码时,它不会从登录重定向到主页。
  • 检查$_SESSION['username']是否有值,删除if然后回显它
  • 运行良好,还有一个错误,谢谢好友@carl Jan
猜你喜欢
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 2017-02-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多