简体   繁体   English

在PHP中处理会话的正确方法

[英]Correct way of handling sessions in PHP

I am using PHP 5 based web application without any framework, all of my admin page and user page has the code below to handle the session. 我正在使用没有任何框架的基于PHP 5的Web应用程序,我的所有管理页面和用户页面均具有以下用于处理会话的代码。 Is it correct way of handling sessions? 这是处理会话的正确方法吗? or any best way to prevent user entering home page after logout? 还是防止用户注销后进入主页的最佳方法? Please suggest us. 请给我们建议。

<?php

if(isset($_SESSION))
{
?>

<html>...</html>

<?php
}
else {
echo 'Session expired';
}
?>

Thanks in advance. 提前致谢。

It would be shorter in this instance to just do: 在这种情况下,这样做会更短:

<?php
session_start();
if(!isset($_SESSION['whatever']))
    die("Session Expired");
?>
<html>..etc.

You don't need to wrap a whole bunch of script with if/else . 您不需要使用if/else包装一堆脚本。

This question is however, off topic because it's opinion-based and not specifically about a technical issue you are facing. 但是,此问题不在主题之列,因为它是基于观点的,而不是专门针对您面临的技术问题。

The problem is that you always have to start with session_start() and as a result the variable $_SESSION might be set. 问题是您必须始终从session_start()开始,因此可能会设置变量$_SESSION

I suggest to store a token to actually show whether or not the user is authenticated so that once the session is destroyed. 我建议存储令牌以实际显示用户是否已通过身份验证,以便一旦会话被销毁。

Code Snippet 代码段

    <?php

        session_start();

        if ($_POST["username"] == "admin" && $_POST["password"] == sha1("password")):


            $_SESSION["authorized"] = true;
            $_SESSION["id"] = session_regenerate_id();

        endif;
    ?>

In this case you can check if the session exist then if the user is authenticated, it is a good practice to regenerate the session id too. 在这种情况下,您可以检查会话是否存在,然后验证用户身份,这也是一种很好的做法,也可以重新生成会话ID。

<?php 
    if(isset($_SESSION) && $_SESSION["authorized"] == true):
        /* What you plan to do here */
    endif;
?>

you're on the right track 你走在正确的轨道上

<?php

    if(isset($_SESSION))
    {
    ?>

    <html>...</html>

    <?php
    }
    else {

echo 'Session expired';

i would organize your lines to be a little more code friendly 我会组织您的行,使其对代码更加友好

<?php
    if(isset($_SESSION)) {
?>

<html>...</html>

<?php
    } else {
    echo 'Session expired';
}

you also don't need to specify <?php; 您也不需要指定<?php; in your php.ini file you can set it so you could just use <?; 您可以在php.ini文件中进行设置,以便只使用<?; once you've made the change you need to restart apache (service or /etc/init.d/httpd restat or windows find xampp for instance and restart apache. 进行更改后,您需要重新启动apache(服务或/etc/init.d/httpd restat或Windows,例如,找到xampp并重新启动apache。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM