I know that in php I can put a variable name inside a quoted string when I use echo, but I apparently can't do this with a session variable. Can anyone explain why?
Here is the code, with the "offending" php commented out:
<?php
session_start();
$test = 100;
$_SESSION['test'] = 200;
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<p><?php echo($test."<br />");?></p>
<p><?php echo("$test"."<br />");?></p>
<p><?php echo($_SESSION['test']."<br />");?></p>
<p><?php //echo("$_SESSION['test']"."<br />");?></p>
</body>
</html>
And the output looks like this:
100
100
200
But if I uncomment the offending code line:
<p><?php echo("$_SESSION['test']"."<br />");?></p>
I get no output and the following error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in - on line 14
So I can go on my merry way knowing how to do it correctly (just keep the session variable outside of the double quotes), but I would really like to understand why this doesn't work for session variables.
Thanks!
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
As @Thariama said, there's no limit on the number of variables; also, there's no limit on the amount of data you can store in a session (I've seen sessions tens of MB in size).
Output: session_destroy() function: It destroys the whole session rather destroying the variables. When session_start() is called, PHP sets the session cookie in browser. We need to delete the cookies also to completely destroy the session. Example: This example is used to destroying the session.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application.
Inside a double-quoted string you must enclose a complex variable (array or object property) in {}
:
<p><?php echo("{$_SESSION['test']}"."<br />");?></p>
This isn't an issue with $_SESSION
specifically, but any array accessed by quoted keys. Note, that you can include a numerically indexed array value with wrapping in {}
, as in "echo $array[2] is two";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With