如何避免 headers 已发送并更改 cookie 相关设置

How to avoid headers already sent and change cookie related settings

我正在尝试创建一个函数来为我的脚本安全地启动一个新的 session 并修改 cookie 设置。

这是函数:

public function sessionStart($sessID, $noCache)
    {
        session_start();

        if($noCache)
        {
            header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
            header("Cache-Control: post-check=0, pre-check=0", false);
            header("Pragma: no-cache");
        }

        // **PREVENTING SESSION HIJACKING**
        // Prevents javascript XSS attacks aimed to steal the session ID
        ini_set('session.cookie_httponly', 1);

        // **PREVENTING SESSION FIXATION**
        // Session ID cannot be passed through URLs
        ini_set('session.use_only_cookies', 1);

        // Uses a secure connection (HTTPS) if possible
        ini_set('session.cookie_secure', 1);

        session_name($sessID);

        // Finally start a new session.
    }

我已经尝试了 'google' 向我展示的所有内容,但我仍然有关于 headers 的错误:

Cannot modify header information - headers already sent

有没有办法让我的功能正常工作?

亲切的问候!

此错误通常是由于您在代码中重复了 session_start()

确保每个脚本只启动一次会话。一种方法是放置一个 echo/logging 系统,这样您就可以看到该函数被命中了多少次。

看这里:PHPaste Snippet.

此外,在 session_start() 之前添加 ini_set([...]) 内容可能是个好主意,因此您要确保它在 运行.

时的行为符合预期