if you remove session_register() calls and replace with $_SESSION assignments, make sure that it wasn't being used in place of session_start(). If it was, you'll need to add a call to session_start() too, before you assign to $_SESSION.
session_register
(PHP 4, PHP 5 < 5.4.0)
session_register — Registrar una o más variables globales con la sesión actual
Descripción
session_register() acepta un número variable de argumentos, cualquiera que pueda ser o una cadena que contenga el nombre de una variable o una matriz que consista en nombres de variables u otras matrices. Por cada nombre, session_register() registra la variable global con ese nombre en la sesión actual.
También se puede crear una variable de sesión estableciendo simplemente el miembro apropiado de la matriz $_SESSION o $HTTP_SESSION_VARS (PHP < 4.1.0).
<?php
// El uso de session_register() está obsoleto
$barney = "Un gran dinosaurio púrpura.";
session_register("barney");
// Se prefiere el uso de $_SESSION, a partir de PHP 4.1.0
$_SESSION["zim"] = "Un invasor de otro planeta.";
// La forma antigua era usar $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["bobesponja"] = "Tiene pantalones cuadrados.";
?>
Si no se llamó a session_start() antes de llamar a esta función, se hará una llamada implícita a session_start() sin parámetros. $_SESSION no imita este comportamiento y requiere que session_start() se use antes.
Esta función ha sido declarada OBSOLETA desde PHP 5.3.0 y ELIMINADA a partir de PHP 5.4.0.
Parámetros
-
name -
Una cadena de contiene el nombre de una variable o una matriz que consiste en nombres de variables u otras matrices.
-
... -
Valores devueltos
Devuelve TRUE en caso de éxito o FALSE en caso de error.
Notas
Si quiere que su script funcione sin tener en cuenta register_globals, necesita usar en su lugar la matriz $_SESSION ya que las entradas de $_SESSION se registran automáticamente. Si su script usa session_register(), no funcionará en entornos donde la directiva de PHP register_globals esté deshabilitada.
Nota: register_globals: Observación importante
Desde PHP 4.2.0, el valor por defecto de la directiva register_globals es off. La comunidad de PHP desaconseja el uso de esta directiva y sugiere el uso de otras formas como superglobals.
Esto registra una variable global. Si no desea registrar una variable de sesión desde dentro de una función, necesita asegurarse de hacerla global usando la palabra clave global o la matriz $GLOBALS[], o use las matrices de sesión especiales como está anotado debajo.
Si está usando $_SESSION (o $HTTP_SESSION_VARS), no use session_register(), session_is_registered(), y session_unregister().
Nota:
Actualmente es imposible registrar variables de recursos en una sesión. Por ejemplo, no se puede crear una conexión a una base de datos y almacenar el id de conexión como una variable de sesión y esperar que la conexión aún sea válida la siguiente vez que se restaure la sesión. Las funciones de PHP que devuelven un recurso están identificadas por tener un tipo de retorno de resource en sus definiciones de función. Una lista de funciones que devuelven recursos está disponible en el apéndice tipos de recursos.
Si se usa $_SESSION (o $HTTP_SESSION_VARS para PHP 4.0.6 o anterior), asigne valores a $_SESSION. Por ejemplo: $_SESSION['var'] = 'ABC';
Ver también
- session_is_registered() - Averiguar si una variable global está registrada en una sesión
- session_unregister() - Deja de registrar una variable global de la sesión actual
- $_SESSION
I've noticed that if you try to assign a value to a session variable with a numeric name, the variable will not exist in future sessions.
For example, if you do something like:
session_start();
$_SESSION['14'] = "blah";
print_r($_SESSION);
It'll display:
Array ( [14] => "blah" )
But if on another page (with same session) you try
session_start();
print_r($_SESSION);
$_SESSION[14] will no longer exist.
Maybe everyone else already knows this, but I didn't realize it until messing around with a broken script for quite a while.
Below is a fix that may be included in older code to make it work with PHP6.
When needed it recreates the functions
- session_register()
- session_is_registered()
- session_unregister()
The functions inside the function fix_session_register() are only available after fix_session_register() has run.
Therefore in PHP<6 where there already is a session_register() nothing happens.
<?php
// Fix for removed Session functions
function fix_session_register(){
function session_register(){
$args = func_get_args();
foreach ($args as $key){
$_SESSION[$key]=$GLOBALS[$key];
}
}
function session_is_registered($key){
return isset($_SESSION[$key]);
}
function session_unregister($key){
unset($_SESSION[$key]);
}
}
if (!function_exists('session_register')) fix_session_register();
?>
[EDIT BY danbrown AT php DOT net: Bugfix provided by "dr3w" on 02-APR-2010: "its [sic] function_exists with an S at the end".]
If you want to store an object into the session, you have to check up that object can be serialized at all.
For example, if your object contains aggregated PDO object (which can't be serialized), you will get an error and no data would be stored.
in addition to function set_session_vars instead of replacing all $var with $_SESSION['var'],
you could get all set session-vars in prevoius scripts with this function
<?php
function get_session_vars() {
$nb_args=func_num_args();
$arg_list=func_get_args();
for($i=0;$i<$nb_args;$i++) {
global $$arg_list[$i] = $_SESSION[$arg_list[$i]];
}
}
?>
You *MUST* notice that
session_register($var)
*IS NOT*
$_SESSION[$var] = $$var;
it is
if (!isset($_SESSION[$var]))
$_SESSION[$var] = $$var;
when migrating from old style code.
If you have an old code with a lot of call to the function session_register(), and you would like to make it compatible with PHP5 or PHP6, instead of rewriting all your code by replacing this function by $_SESSION['var']="val"; you could use the function set_session_vars(), that is used exactly the same way than session_register() (but there is no implicit call to session_start() ).
<?php
function set_session_vars() {
$nb_args=func_num_args();
$arg_list=func_get_args();
for($i=0;$i<$nb_args;$i++) {
global $$arg_list[$i];
$_SESSION[$arg_list[$i]] = $$arg_list[$i];
}
}
?>
For those of you who use this function (session_register that is), even though the manual does specify that this function implicitly calls session_start(), I just wanted to reiterate that fact. It is also important to know that if you ever switch from session_register to using $_SESSION, make sure to call session_start before adding items to the $_SESSION variable, because unlike session_register, no implicit call to session_start is done.
Another reason I explain this is because I ran into a problem in which you can add items to the $_SESSION variable all you want, but if session_start is not called before adding them, they will not actually be saved to the session. Using the same code, though, and replacing the $_SESSION assignments with session_register without calling session_start WILL save that info to the session.
It would be nice to have PHP check for writes to the $_SESSION variable and complain with a warning if session_start hasn't been called.
Make sure you put session_start() at the beggining of your script.
My sessions kept unsetting and I finally figured out why.
On my script, session_start() has to be said and uses cookies to set the session.
But I was outputting html prior to calling session_start(), which prevented it from succeeding becouse it uses the header function to place the cookies.
Once html has been outputed, session_start() can't use the header function to set cookies, hence session_start() fails and no session can be started.
Please note that if you use a "|" sign in a variable name your entire session will be cleared, so the example below will clear out all the contents of your session.
<?php
session_start();
$_SESSION["foo|bar"] = "foo";
?>
It took me quite some time finding out why my session data kept disappearing. According to this bugreport this behaviour is intended.
http://bugs.php.net/bug.php?id=33786
If you are using sessions and use session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This basically means that these objects can show up on any of your pages once they become part of your session.
