Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echoing session variables in php [duplicate]

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!

like image 334
doxguy Avatar asked Nov 06 '11 16:11

doxguy


People also ask

Why session_start () is used in PHP?

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.

How many session variables can you have PHP?

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).

What is PHP session_start () and Session_destroy () function?

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.

What is $_ session variable in PHP?

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.


1 Answers

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";

like image 189
Michael Berkowski Avatar answered Sep 19 '22 18:09

Michael Berkowski