3

I am trying to pass on the value of one variable from one PHP page to another PHP page, but for some reason, it's not working..

Here's my code for phpOne.php:

<?php
    $x = 100;
    $_SESSION['sessionVar'] = $x;
    echo "$x";
?>

And here's my code for phpTwo.php:

<?php
$x = $_SESSION['sessionVar'];
echo "$x";
?>

Thanks in-advance! Tom!

4
  • 1
    When you say its not working, what isn't? Elaborate.. Any error messages? Commented May 13, 2013 at 13:48
  • 6
    Do you have session_start() in those pages, too? Commented May 13, 2013 at 13:48
  • As andrewsi said, you have to use session_start() in every page, that uses the $_SESSION variable. Put it on the first line after <?php. Basically before any output. Commented May 13, 2013 at 13:48
  • No, I didn't. Thanks a bunch! Commented May 13, 2013 at 13:53

4 Answers 4

4

You need to call session_start(); on both pages.

Sign up to request clarification or add additional context in comments.

Comments

3

Use this:

session_start();

to start up your session. You need to add this on all pages that need to access the $_SESSION[] variables, otherwise it won't work.

Comments

2
<?php
  session_start();
  $x = 100;
  $_SESSION['sessionVar'] = $x;
  echo "$x";
?>


<?php
  session_start();
  $x = $_SESSION['sessionVar'];
  echo "$x";
?>

You have to init session_start() to make use of the session variables.

Comments

2

Everyone is right. Session variables are stored in the server with a reference key. The key(known as PHP SESSION ID) is stored in the server as well as the browser cookie. Each time the browser sends the key to the server. If the server gets a session_start() without a key then it initiates a new session. Whereas if the browser page has the key then it restores the session. Which is why it becomes essential that you call the session_start() in both pages. I hope this clears it up!! Good luck

Read this for deeper explanation (if you want) : http://www.php.net/manual/en/intro.session.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.