PHP COTW: HTTP_POST_VARS and HTTP_GET_VARS

Over the following weeks I will be covering PHP code which stands out to myself and some code which I use regularly. These PHP codes will be mentioned every week with an explanation on their uses. The section is called “PHP code of the week“.


We begin with our first PHP code of the week: HTTP_POST_VARS and HTTP_GET_VARS. Without these two functions we wouldn’t be able to get data from forms or simplify the way we specify user input in our code.

HTTP_POST_VARS is the function we call when we want to retrieve variable input from a form that the user has submitted. Say we have a field in the form called username. To retrieve the value of username we would write it as:

$username = $HTTP_POST_VARS['username'];

So we have the username fields value being assigned to a local variable $username.


HTTP_GET_VARS
is commonly used when searching forums, looking up user names, etc so you have most likely seen it been used. It is a simple way to input values into your code and is done by placing a question mark (?) and variable name and the value after the file we are requesting.

http://www.test.com/view_user.php?userid=5

In the above case, we can see that we are requesting the view_user.php file and are wanting to find more information on the userid number 5.


The inside code would look like:

$user_id = $HTTP_GET_VARS['userid'];

That’s pretty simple, we have the userid variable being assigned to the local variable $user_id.


Using HTTP_GET_VARS you are also able to retrieve more than one variable by placing a ampersand sign after each value. Such as:

http://www.test.com/view_user.php?userid=5&findtopics=1&findposts=2


So there you go, you now know how to retrieve user data.

If you are requesting the values and say the user didn’t input anything in the POST/GET request, 0 (false) is assigned to the local variables.

Note: These examples aren’t recommended to be placed directly into code as there are security issues. You should use functions such as htmlspecialchars, intval and str_replace before touching the variables. These functions will be covered in the next PHP code of the week.

Leave a Reply