Thomas Gouder
Thomas Gouder

Reputation: 125

PHP - Passing variables from one page to another

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!

Upvotes: 3

Views: 19751

Answers (4)

Saifur Rahman Mohsin
Saifur Rahman Mohsin

Reputation: 1011

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

Upvotes: 2

Firebowl2000
Firebowl2000

Reputation: 312

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

Upvotes: 2

Borniet
Borniet

Reputation: 3546

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.

Upvotes: 3

Useless Intern
Useless Intern

Reputation: 1302

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

Upvotes: 4

Related Questions