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.
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';
session_register
01-Jun-2006 08:10
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.
