PHP Global Variables

Written by admin on December 31st, 2007 in General.

PHP ( Hypertext Pre-Processor) uses variables to store information in a page. Standard variables can be called anything for example: $myvariable but PHP also has some global variables. These are variables that are declared on every PHP page and are used differently. Tthe 3 main global variables are: $_GET, $_POST and $_SESSION. All of these 3 global variables are arrays. Global variables can be used from page to page without havign to declare them again. The ones we are going to look at closely are $_GET and $_POST.

$_GET refers to the URL of the web page. Within the $_GET array the attributes of the URL are stored. For example:

http://www.pdstudios.net/index.php?myname=admin

That URL has an attribute in it. The attribute is myname which equals admin. To obtain this information from the URL we use $_GET.

To get the attribute names myname we use the following syntax: $_GET[’myname’]. We use it exactly like a normal array. You can then use this for whatever it needs to be used for and the value can even be stored in a normal PHP variable.

Now lets look at $_POST. $_POST is used by HTML forms to process the information with PHP. Again these are arrays and accessing the information is similar to $_GET. $_POST is a hidden variable from which a PHP document can access. the information is carried from one page to the other but only once. to access $_POST we use the same as $_GET.

$_POST[’myname’]

So to get the values into the $_POST array we use HTML forms. The name of the form field is the name of the array in the $_POST variable.

POST and GET example

For example if I had a HTML form with a text field named country and I submitted the form, on the next page I could get that information by asking for $_POST[’location’]. To get you HTML form to use POST as its delivery method you must have the following attribute in your <form> tag: method=”POST”

$_SESSION is much different from the other two and is more complex to use. This global variable uses sessions to function. Recommend you read up on the PHP Sessions tutorial before continuing.

$_SESSION is exactly the same as $_POST and $_GET for retrieving information but setting the information is easier. Setting the information is similar to setting a normal PHP variable but using $_SESSION[’name’]. You must have your session declared on each page that you want this information to be used on, if not the information will not be available on that page. The $_SESSION variable can go over as many pages as you want it to as long as the session is declared.

Thats all there is to it. With this information you can make simple but effective scripts. Enjoy, if you have questions please leave a comment or ask for help on our community forums.

Leave a Reply

You must be logged in to post a comment.



Site Navigation