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];
}
}
?>
session_register
(PHP 4, PHP 5)
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 de los cuales puede ser o una cadena que contiene el nombre de una variable, o una matriz que consista de nombres de variables u otras matrices. Para cada nombre, session_register() registra la variable global con ese nombre en la sesión actual.
Puede crear también una variable de sesión, simplemente definiendo el miembro apropiado de $_SESSION o la matriz $HTTP_SESSION_VARS (PHP < 4.1.0).
<?php
// El uso de session_register() es considerado obsoleto
$barney = "Un dinosaurio grande y violeta.";
session_register("barney");
// Se prefiere el uso de $_SESSION, a partir de PHP 4.1.0
$_SESSION["zim"] = "Un invasor de otro planeta.";
// El modo antiguo era usar $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["bob_esponja"] = "Él tiene pantalones cuadrados.";
?>
Si session_start() no fue llamada antes de que esta función sea llamada, se realizará un llamado implícito a session_start() sin parámetro alguno. $_SESSION no imita este comportamiento y requiere session_start() antes de su uso.
Lista de parámetros
- nombre
-
Una cadena que contiene el nombre de una variable o una matriz consistente de nombres de variables u otras matrices.
- ...
-
Valores retornados
Devuelve TRUE si todo se llevó a cabo correctamente, FALSE en caso de fallo.
Notes
Si desea que su script funcione independientemente de register_globals, necesita usar en su lugar la matriz $_SESSION, dado que las entradas de $_SESSION son registradas automáticamente. Si su script usa session_register(), no funcionará en entornos en donde la directiva PHP register_globals esté deshabilitada.
Note: register_globals: Nota importante
Desde PHP 4.2.0 el valor por defecto de la directiva register_globals es off. La comunidad PHP anima a todos a no confiar en esta directiva y usar en su lugar superglobals.
Esto registra una variable global. Si desea registrar una variable de sesión desde el interior de una función, necesita asegurarse de hacerla global usando la palabra clave global o la matriz $GLOBALS[], o usar las matrices de sesión especiales, como se anota a continuación.
Si está usando $_SESSION (o $HTTP_SESSION_VARS), no use session_register(), session_is_registered(), ni session_unregister().
Note: Actualmente es imposible registrar variables de recurso en una sesión. Por ejemplo, no puede crear una conexión a una base de datos y almacenar la id de conexión como una variable de sesión y esperar que la conexión aun sea válida la próxima vez que la sesión sea restaurada. Las funciones PHP que devuelven un recurso se identifican por tener un tipo de retorno de resource en su definicón de función. Una lista de funciones que devuelven recursos está disponible en el apéndice tipos de recurso.
Si $_SESSION (o $HTTP_SESSION_VARS para PHP 4.0.6 o versiones anteriores) es usado, asigne valores a $_SESSION. Por ejemplo: $_SESSION['var'] = 'ABC';
Ver también
- session_is_registered() - Comprueba si una variable está registrada en la sesión
- session_unregister() - Desregistrar una variable de la sesión actual
- $_SESSION
session_register
26-May-2009 02:15
19-May-2009 11:15
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.
01-Jun-2006 08:10
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.
11-Apr-2006 09:04
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
21-Nov-2004 09:40
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.
12-Nov-2004 07:05
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.
