简体   繁体   中英

PHP $_SESSION variables are not being passed between pages

I am working on a school project where I need my .php pages communicating. I have header.php where I set connection to the database and start the session. 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)

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. I see many people have complained about this, but I still can't find the solution.

login-form.php

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

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.

The variables are probable not set, because you haven't activate the session variables with session_start().

session_id() == '' is not a correct conditional . 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. You said

PHP $_SESSION variables are not being passed between pages

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. ie the command to read those data from the server is needed.

Since my header.php file included "connection.php" file, I put

session_start();

at the beginning of connection.php and deleted it from header.php file. 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. You could try faking entries in the PHP superglobals, but that is wholly inadvisable. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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