Skip to main content

Passing variables between pages with PHP

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 store data on the server for access between php scripts on different web-pages.

It’s important to note that the session_start line must be used prior to using the $_SESSION superglobal.


Cookies differ from sessions in that they store the data on the client, instead of the server, and therfore are relatively un-safe.

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.


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 :

Then, on Page 2 the variables can be retrieved as :

Both methods, GET and POST, are insecure because it’s possible to tamper with this data before sending it to the server.


HTML Forms

Leave a Reply

Your email address will not be published. Required fields are marked *