简体   繁体   English

PHP $ _SESSION变量未在页面之间传递

[英]PHP $_SESSION variables are not being passed between pages

I am working on a school project where I need my .php pages communicating. 我在一个学校项目中工作,需要我的.php页面进行通信。 I have header.php where I set connection to the database and start the session. 我有header.php,可在其中设置与数据库的连接并启动会话。 In order to start the session only once, I've used this: 为了只启动一次会话,我使用了以下方法:

if(session_id() == '') {
    session_start();
}

PHP version is PHP 5.3.10-1 ubuntu3.18 with Suhosin-Patch (cli) PHP版本是带有Suhosin-Patch(cli)的PHP 5.3.10-1 ubuntu3.18

I am trying to pass some $_SESSION variables between pages, but they keep being unset when I try to use them on a page that doesn't set them. 我试图在页面之间传递一些$ _SESSION变量,但是当我尝试在未设置它们的页面上使用它们时,它们始终保持未设置状态。 I see many people have complained about this, but I still can't find the solution. 我看到许多人对此表示抱怨,但仍然找不到解决方案。

login-form.php 登录-form.php的

    <?php
        if (isset($_SESSION["login-error"])) {
            echo '<p>'.$_SESSION["login-error"].'</p>';
        }   
    ?>

login.php 的login.php

 $_SESSION["login-error"]= "Username or password incorrect";

There is a code snippet of what is not working for me. 有一段代码对我不起作用。 Thanks 谢谢

You can try this. 你可以试试看

In your function file put this 在您的功能文件中放入

function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

Then you can run this in every page you want session started 然后,您可以在要启动会话的每个页面中运行此命令

if ( is_session_started() === FALSE ) session_start();

With this I think you should be good to go on starting your session across pages. 以此为基础,我认为您应该跨页面开始会话。 Next is to ensure you set a session to a value. 接下来是确保将会话设置为一个值。 If you are not sure what is unsetting your sessions you can try var_dump($_SESSION) at different parts of your code so you be sure at what point it resets then know how to deal with it. 如果不确定什么会导致会话var_dump($_SESSION)可以在代码的不同部分尝试var_dump($_SESSION) ,以便确定在什么时候复位,然后知道如何处理它。

The variables are probable not set, because you haven't activate the session variables with session_start(). 这些变量可能未设置,因为您尚未使用session_start()激活会话变量。

session_id() == '' is not a correct conditional . session_id() == ''不是正确的条件。 Use instead: 改用:

 if (!isset($_SESSION)) { session_start();}

if you have session started then you can set a session variable 如果您已开始会话,则可以设置会话变量

  if (!isset($_SESSION["login-error"])) { $_SESSION["login-error"]= "Username or password incorrect";}

Before you call $_SESSION["login-error"], type session_start() , just for testing, to find when the session signal is missing. 在调用$ _SESSION [“ login-error”]之前,键入session_start() (仅用于测试)以查找缺少会话信号的时间。 You said 你说

PHP $_SESSION variables are not being passed between pages PHP $ _SESSION变量未在页面之间传递

session_start() and SESSION variables needs to be included at the beginning of EVERY page or at the place where SESSION variables are being called (through a common file, bootstrap, config or sth) at the beginning of EVERY page. session_start()和SESSION变量需要包含在EVERY页面的开头,或者在EVERY页面的开头被调用SESSION变量的位置(通过通用文件,bootstrap,config或sth)。 ie the command to read those data from the server is needed. 即需要从服务器读取那些数据的命令。

Since my header.php file included "connection.php" file, I put 由于我的header.php文件包含“ connection.php”文件,因此我将

session_start();

at the beginning of connection.php and deleted it from header.php file. 在connection.php的开头,并将其从header.php文件中删除。 Now it works fine. 现在工作正常。 Thanks all for your help! 感谢你的帮助!

PHP sessions rely on components of HTTP, like Cookies and GET variables, which are clearly not available when you're calling a script via the CLI. PHP会话依赖于HTTP的组件,例如Cookies和GET变量,当您通过CLI调用脚本时,这些组件显然不可用。 You could try faking entries in the PHP superglobals, but that is wholly inadvisable. 您可以尝试伪造PHP超全局变量中的条目,但这是完全不建议的。 Instead, implement a basic cache yourself. 而是自己实现一个基本的缓存。

<?php
class MyCache implements ArrayAccess {
    protected $cacheDir, $cacheKey, $cacheFile, $cache;

    public function __construct($cacheDir, $cacheKey) {
        if( ! is_dir($cacheDir) ) { throw new Exception('Cache directory does not exist: '.$cacheDir); }
        $this->cacheDir = $cacheDir;
        $this->cacheKey = $cacheKey;
        $this->cacheFile = $this->cacheDir . md5($this->cacheKey) . '.cache';

        // get the cache if there already is one
        if( file_exists($this->cacheFile) ) {
            $this->cache = unserialize(file_get_contents($this->cacheFile));
        } else {
            $this->cache = [];
        }
    }

    // save the cache when the object is destructed
    public function __destruct() {
        file_put_contents($this->cacheFile, serialize($this->cache));
    }

    // ArrayAccess functions
    public function offsetExists($offset) { return isset($this->cache[$offset]); }
    public function offsetGet($offset) { return $this->cache[$offset]; }
    public function offsetSet($offset, $value) { $this->cache[$offset] = $value; }
    public function offsetUnset($offset) { unset($this->cache[$offset]); }
}

$username = exec('whoami');
$c = new MyCache('./cache/', $username);

if( isset($c['foo']) ) {
    printf("Foo is: %s\n", $c['foo']);
} else {
    $c['foo'] = md5(rand());
    printf("Set Foo to %s", $c['foo']);
}

Example runs: 示例运行:

# php cache.php
Set Foo to e4be2bd956fd81f3c78b621c2f4bed47

# php cache.php
Foo is: e4be2bd956fd81f3c78b621c2f4bed47

This is pretty much all PHP's sessions do, except a random cache key is generated [aka PHPSESSID] and is set as a cookie, and the cache directory is session.save_path from php.ini . 这几乎是所有PHP会话的工作,除了会生成一个随机缓存键[aka PHPSESSID]并将其设置为cookie,并且缓存目录是php.ini session.save_path

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

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