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 uma ou mais variáveis globais na sessão atual
Descrição
session_register() aceita um número de argumentos variáveis, algund deles podem ser ou uma string com o nome da variável ou uma matriz de nomes de variáveis ou outras matrizes. Para cada nome, session_register() registra a variável global com o nome na sessão atual.
Se você quer que seu script funcione independentemente do uso de register_globals, você precisa usar a matriz $_SESSION já que $_SESSION é automaticamente registrada. Se o seu script usa session_register(), ele não irá funcionar em ambientes onde a diretiva de configuração register_globals esteja desabilitada.
Nota: Nota importante sobre register_globals:
Desde o PHP 4.2.0, o valor padrão para a diretiva register_globals é off e foi completamente removida a partir do PHP 6.0.0. A comunidade do PHP desencoraja desenvolvedores a confiar nesta diretiva, e encoraja o uso de outros meios, como em superglobals.
Isto registra uma variável global. Se você quiser registrar uma variável dntro de uma função, você deve certificar-se de faze-la global, usando global ou usando a matriz $GLOBALS[], ou usando a matriz especial para seções($_SESSION) como mostrado abaixo.
Se você esta usando $_SESSION (ou $HTTP_SESSION_VARS), não use session_register(), session_is_registered() e session_unregister().
Esta função retorna TRUE quando todas de suas variáveis são registradas sem erro.
Se session_start() não foi chamada antes desta função ser chamada, uma chamada implícita para session_start() sem parâmetros será feita. $_SESSION não imita isto e necessita que session_start() seja chamada antes de usar.
Você também pode criar variáveis de sessão simplesmente definindo o membro apropriado de $_SESSION ou $HTTP_SESSION_VARS (PHP < 4.1.0) matriz.
<?php
// O uso de session_register() esta obsoleto
$barney = "Um grande dinossauro púrpura.";
session_register("barney");
// O uso de $_SESSION é recomendado, apartir do PHP 4.1.0
$_SESSION["zim"] = "Um invasor de outro planeta.";
// A maneira antiga é usar $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "Ele conseguiu calças ajustadas.";
?>
Nota: Não é possível registrar atualmente variáveis resource numa sessão. Por exemplo, você não pode criar uma conexão para um banco de dados e guardar a id de conexão como uma variável de sessão e esperar que a conexão ainda esteja válida na próxima vez que a sessão estiver restaurada. Funções do PHP que retornam uma resource são identificadas por conterem um retorno do tipo resource em suas definições de função. Uma lista de funções que retornam resources estão disponíveis no apêndice tipos resources.
Se $_SESSION (ou $HTTP_SESSION_VARS para PHP 4.0.6 ou inferior) é usada, para variável definida variable com $_SESSION. i.e. $_SESSION['var'] = 'ABC';
Veja também session_is_registered(), session_unregister() e $_SESSION.
session_register
01-Jun-2006 10:10
11-Apr-2006 11: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 10: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 08: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.
