Variables From External Sources
HTTP Cookies
PHP transparently supports HTTP cookies as defined by » RFC 6265. Cookies are a
mechanism for storing data in the remote browser and thus
tracking or identifying return users. It is possible to set cookies using
the setcookie() function. Cookies are part of
the HTTP header, so the SetCookie function must be called before
any output is sent to the browser. This is the same restriction
as for the header() function. Cookie data
is then available in the appropriate cookie data arrays, such
as $_COOKIE as well as in $_REQUEST.
See the setcookie() manual page for more details and
examples.
Note:
As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the names
of incoming cookies are no longer url-decoded for security reasons.
If multiple values should be assigned to a single cookie variable,
they can be assigned as an array. For example:
That will create two separate cookies although MyCookie will now
be a single array in the script. If just one cookie should be set
with multiple values, consider using serialize() or
explode() on the value first.
Note that a cookie will replace a previous cookie by the same
name in the browser unless the path or domain is different. So,
for a shopping cart application a counter may be kept,
and passed along. I.e.
Example #4 A setcookie() example
<?php
if (isset($_COOKIE['count'])) {
$count = $_COOKIE['count'] + 1;
} else {
$count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>
Dots in incoming variable names
Typically, PHP does not alter the names of variables when they
are passed into a script. However, it should be noted that the
dot (period, full stop) is not a valid character in a PHP
variable name. For the reason, look at it:
<?php
$varname.ext; /* invalid variable name */
?>
Now, what the parser sees is a variable named
$varname, followed by the string concatenation
operator, followed by the barestring (i.e. unquoted string which
doesn't match any known key or reserved words) 'ext'. Obviously,
this doesn't have the intended result.
For this reason, it is important to note that PHP will
automatically replace any dots in incoming variable names with
underscores.
Determining variable types
Because PHP determines the types of variables and converts them
(generally) as needed, it is not always obvious what type a given
variable is at any one time. PHP includes several functions
which find out what type a variable is, such as:
gettype(), is_array(),
is_float(), is_int(),
is_object(), and
is_string(). See also the chapter on
Types.
HTTP being a text protocol, most, if not all, content that comes in
Superglobal arrays,
like $_POST and $_GET will remain
as strings. PHP will not try to convert values to a specific type.
In the example below, $_GET["var1"] will contain the
string "null" and $_GET["var2"], the string "123".
/index.php?var1=null&var2=123