How to fix the session_register() deprecated issue

2019-01-01 09:01发布

问题:

How to fix the session_register() deprecated problem in PHP 5.3

回答1:

Don\'t use it. The description says:

Register one or more global variables with the current session.

Two things that came to my mind:

  1. Using global variables is not good anyway, find a way to avoid them.
  2. You can still set variables with $_SESSION[\'var\'] = \"value\".

See also the warnings from the manual:

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

This is pretty important, because the register_globals directive is set to False by default!

Further:

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

and

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().



回答2:

Use $_SESSION directly to set variables. Like this:

$_SESSION[\'name\'] = \'stack\';

Instead of:

$name = \'stack\';
session_register(\"name\");

Read More Here



回答3:

before PHP 5.3

session_register(\"name\");

since PHP 5.3

$_SESSION[\'name\'] = $name;


回答4:

if you need a fallback function you could use this

function session_register($name){
    global $$name;
    $_SESSION[$name] = $$name;
    $$name = &$_SESSION[$name]; 
}


回答5:

To complement Felix Kling\'s answer, I was studying a codebase that used to have the following code:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        session_register($var);
    }
} else if (!(empty($start_vars))) {
    session_register($start_vars);
}

In order to not use session_register they made the following adjustments:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        $_SESSION[$var] =  $GLOBALS[$var];
    }
} else if (!(empty($start_vars))) {
    $_SESSION[$start_vars] =  $GLOBALS[$start_vars];
}


回答6:

We just have to use @ in front of the deprecated function. No need to change anything as mentioned in above posts. For example: if(!@session_is_registered(\"username\")){ }. Just put @ and problem is solved.