dongraa1986 2013-08-25 01:33
浏览 85

正确的$ _SESSION身份验证

What is the proper way to authenticate users? As in, setting a page whereby only logged in users can view?

Does this work?

<?php
session_start();
if(!isset($_SESSION[username]) || empty($_SESSION[username]) || !isset($_SESSION[id]) || empty($_SESSION[id]))
{
session_destroy();
session_unset();
die('You\'re not authorized to view this page!');
}
?>

<?php
echo"Can I freely, and safely write my content here? Will it be properly authenticated with my code above?";
?>

But my question is, if I use the above code, can I freely add my content below the code? And is there any other better way to do this?

I have another code whereby I do a

session_destroy();
header("Location: logout.php");
{and then I echo my content below; where logged in users can see}

But I'm just wondering if, once I do that, does it mean users will not be able to see my content below?

Thanks!

  • 写回答

1条回答 默认 最新

  • doumingo04696 2013-08-25 02:10
    关注

    You are correct, but you are a bit verbose in your strategy. Here is a simpler way.

    <?php
    session_start();
    if(empty($_SESSION['username'])) 
    {
      echo "Not allowed."; // possible redirect to login page.
      exit; 
    }
    
    //Authenticated stuff here.
    

    To logout, just clear the username.

    $_SESSION['username'] = "";
    

    Normally, you don't need to worry about cleaning up the internal PHP session cache. PHP has a periodic script that runs in the background on the server to handle that for you.

    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私