Let’s assume a PHP variable `$foo` on `page1.php`. There is a form on this page which posts on `page2.php`. Since HTTP is stateless, webpages are disconnected and this implies that `page2.php` won’t be aware of the existence of `page1.php` or any data thereof. However, `page2.php` can still access the variables from the `page1.php` script using the methods discussed here.
Sessions
Sessions store data on the server for access between php scripts on different web-pages.
// Page 1 session_start(); $_SESSION['foo'] = $foo; // Page 2 session_start(); $foo = $_SESSION['foo'];
It’s important to note that the `session_start` line must be used prior to using the `$_SESSION` superglobal.
Cookies
Cookies differ from sessions in that they store the data on the client, instead of the server, and therfore are relatively un-safe.
// Page 1 setcookie('foo', $foo); // Page 2 $foo = $_COOKIE['foo'];
Cookies maybe preferred over sessions in situations where data needs to persist. However, it’s possible to avoid cookies by storing the data in a database and retrieving it using an id or username.
GET and POST
The variable can either be added as a *GET* parameter in the link to Page 2 :
<a href=”page2.php?foo=<?php echo urlencode($foo);?>”>Go to Page 2</a>
Or, a hidden field can be created in a form that posts to Page 2 :
<form method="post" action="page2.php"> <input type="hidden" name="foo" value=<?php echo $foo;?>> <input type="submit" </form>
Then, on Page 2 the variables can be retrieved as :
// GET method $foo = $_GET['foo']; // POST method $foo = $_POST['foo']; // GET, POST or COOKIE $foo = $_REQUEST['foo'];
Both methods, GET and POST, are insecure because it’s possible to tamper with this data before sending it to the server.