dongzhu6900 2019-01-18 11:38
浏览 45
已采纳

无法使用密码保护页面/区域

I'm trying to create a password protected area of a website. I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.

My code for the login page is:

     if (isset($_POST['submit']))
        {     
    include("config.php");
    session_start();
    $username=$_POST['username'];
    $password=$_POST['password'];
    $passwordc=md5($password);        

    $query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
     $result2 = $conn->query($query);

    if ($result2->num_rows != 0) {          

    $_SESSION["username"] = $user;
      echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";   
    }else{
      echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
    }

    }

It seems to work (correctly redirects if username and password matches, shows alert if not). What I fail to do, is actually protect my pages from display if session is not active.

   session_start();
if (!$_SESSION["username"]) {
    header("Location: login.php");
}

I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files. Any help would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • donglei_0507 2019-01-18 13:07
    关注

    modify your login code as

     if (isset($_POST['submit']))
        {     
       include("config.php");
      $username= $crud->escape_string($_POST['username']);
      $password= $crud->escape_string($_POST['password']);
       $passwordc=md5($password); 
       $query = "SELECT username FROM admin WHERE username='$username' AND 
       password='$passwordc'";
       $result2 = $conn->query($query);
      if ($result2->num_rows != 0) { 
       session_start();         
      $_SESSION["username"] = $user;
      header("Location:admin_view.php");   
    }else{
      $Message = urlencode("user name password invalid!");
                          header("Location:login.php?Message=".$Message);
    }
       }
    

    if your values successfully stored in session then you can use like

    session_start();
    if(!isset($_SESSION['username'])) 
      {
      header("Location: login.php");  
      }
    

    on everypage top you must store name from query into session

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置