[thelist] PHP sessions syntax

Paul Waring paul at xk7.net
Sun Jul 22 07:40:50 CDT 2007

On Sun, Jul 22, 2007 at 08:24:46AM -0400, Nan Harbison wrote:
> I have always used:
>   session_register ('user_id');
>   session_register ('first_name');
> but now I have read you can just set session vars to something, like:
> $_SESSION["first_name"] = "Nan";
> Is the way I have always used been deprecated or can I still safely use it?

Use of session_register is deprecated, as it states on the manual page:


"// Use of session_register() is deprecated"

You should assign variables to the $_SESSION array instead, because
session_register relies on register_globals being enabled - the default
value for this flag is 'off' as of 4.2.0 and it will be removed entirely
in PHP 6 so you won't be able to turn it on again. You will have to call
session_start manually though on each page where you want to access
$_SESSION variables (session_register will do this automatically for
you so be aware of this if you are going from one method to the other).

> Another question, do I need to use:
> ["real_name"], ['real_name'] or [real_name] - double or single quotes, or no
> quotes. IIRC, $HTTP_SESSION_VARS did not use quotes at all. I have seen
> single and double quotes used, but don't know if there is a difference?

Double quotes will cause any variables within the quotes to be
interpolated, so for example:

$var = "bob";
echo "Hello $var";

Will print 'Hello Bob' (without the quotes).

Single quotes will not cause anything to be interpolated, so:

$var = "bob";
echo 'Hello $var';

Will print 'Hello $var' (again without the quotes).

So if you're using a simple string to access an array index you should
really use single quotes (e.g. $_SESSION['name']) to save PHP having to
check for anything which needs to be interpolated. However, I don't know
whether using double quotes where you don't need to causes a significant
performance hit - I suspect not.

You should *never* use $_SESSION[name] to access the index 'name', this
will throw an E_NOTICE error because PHP will look for a constant called
'name' (i.e. something like define('name', 'some value')) and then fall
back to using the literal string 'name' instead. Although you probably
won't see these errors because they're supressed by default, your code
is fundamentally broken and will throw lots of errors if moved to a
server which enables all PHP error messages to be displayed/logged.

So in summary: use $_SESSION not session_register, use single quotes
unless you've got variables contained within the quotes - in which case
use doubles, and never *ever* use constants as array indexes when you
mean a literal string (unless you do actually have a constant with that
name defined).


More information about the thelist mailing list