I'm just starting out, so please forgive if this is a silly question.
I'm learning by reading a book and watching a video series that may be slightly out-dated.
The instructions given in certain cases where more than one page is involved use regular variable syntax, but that syntax does not work unless I use the syntax mentioned in the title of this post.
Example from the video includes:
Page 1:
<?php
setcookie("color","blue");
?>
Page 2:
<?php
echo $color;
?>
This does not work for me. However, if I change things using the other syntax, it does work.
Example from changes to variable syntax that makes it work:
Page 1:
<?php
setcookie("color","blue");
?>
Page 2:
<?php
echo $_COOKIE["color"];
?>
So my question is, what is this syntax (ex: $_COOKIE["color"]) that I am using? What is it called and what/how does it work exactly?
I realize this has something to do with sessions, but am too novice to understand beyond that.
Thank you for your help!
They are called Superglobals, they are "special" variables that are always defined.
http://php.net/manual/en/language.variables.superglobals.php
The first example can work if the evil, evil register_globals is enabled:
http://php.net/manual/en/security.registerglobals.php
If you are learning PHP from a source that is using register_globals, I suggest you find another source.
These are called Superglobals. They are global arrays that are available anywhere, without explicitly defining them using global()
. There are sevearl available, for cookies, uploaded files, POST variables, etc.
For more information, it's probably best to refer to the PHP manual: http://php.net/superglobals.
Yes, the example does not work because it is outdated. In PHP, there is a setting called register_globals
which makes this feature work, but it is not recommended to use it.
The syntax you are talking about ($_COOKIE["color"]
) is the syntax to get the element of an (associative) array. $_COOKIE
itself is a superglobal array, and it always stores the values of cookies that were included in the HTTP request.
Sessions is something else, cookies can be used to maintain a session.
The first type of syntax, where you just "find the variables already there" is dependent on a PHP feature called register globals. This feature was introduced a long time ago as a convenience to novices, but it has been the source of many security issues and has been deprecated for some time now (in fact, support for this mode has been totally removed in the upcoming version PHP 5.4). For a very quick overview, read "how does register_globals affect me?" in the FAQ.
The other way of accessing "environment" variables (i.e. those originating from the current HTTP request or the server setup) is by accessing the superglobal variables; this page is also linked to from the register globals piece above.
If you are reading tutorials that depend on register globals being active you should immediately stop reading them and find better and more recent material.