PHP登录和会话 [英] PHP Login and session

查看:80
本文介绍了PHP登录和会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,晚上

我被困住了,我需要PHP方面的帮助.

I'm stuck and I need some help in PHP.

我正在尝试编写一个管理仪表板.而且我想检查用户是否已登录,如果没有,请重定向到登录页面.

I am trying to code up an admin dashboard. And I want to check if user is logged in, if not , redirect to the login page.

我的index.php是这样的:

My index.php is this:

<?php
$pagename ="Index";

@require_once('inc/head.php');
?>
<body>
CONGRATS! Welcome to the Admin dashboard.
</body>
</html>

我的登录页面:

<?php
$pagename = "login";
$adminUser = "admin";
$adminPass = "admin";

@require_once('inc/head.php');

// If POST is submitted and IDs match the ones set
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST["username"] == $adminUser && $_POST["password"] == $adminPass)

    {
    session_start();
    $_SESSION["username"] = $adminUser;
    $_SESSION["login"] = true;
    echo '<script>alert("Congrats, you logged in");
    window.location = "index.php"; </script>';

 /* I skip the line underneath because for unknown reasons my code 
  Doesn't fully run through. So I redirected with the JS above instead.

  header("Location: index.php");
    exit(); */
    }else{
    echo '<script>alert("Incorrect username or password!'");</script>';
    }   
}
?>

<html>
<!-- login page here -->
</html>

这是我的head.php:

And here goes my head.php:

<?php

  // If we AREN'T on the login page , check if session exist. If not send to login
if($pagename != "login")
{       if(!$_SESSION['login'])
     {
        header('location: login.php');  
        exit();
     }
}
?>

这有很多问题,我知道,但到目前为止,我正在尝试解决我的登录问题.每当我登录时,都会弹出JS窗口,提示我已成功登录,但是我没有重定向到索引.我认为我确实发送到了index.php(没有理由将我的JS重定向到NOT函数),但是我的索引使我立即回到登录状态,而我不明白为什么.

There is alot of things wrong with this and I know but as of now I'm trying to fix my login in issue. Whenever I log in I get the JS pop up that says I successfully logged in, but I don't get redirected to the index. I think I do get sent to my index.php ( there's no reason for my JS redirect to NOT function ) but my index sends me right back to login and I don't understand why.

推荐答案

head.php 页面中的启动会话.

head.php

<?php
if($pagename != "login") {
  session_start();
  if(!$_SESSION['login']) {
    header('location: login.php');  
    exit();
  }
}
?>

这篇关于PHP登录和会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆