Now, let’s get to the main reason you want to learn a server scripting language. You want to learn how to take user input and do something with it right? PHP POST, GET, and REQUEST are the primary ways to take input from the user. You can use these variables to correlate with form element data or strings in the url. Once PHP receives that input, you can call these variables to get their values to process the input. But first, we should start with how forms work. Submitting a form is really easy, so let’s get to it.
That is a very condensed version of how to handle forms. We have to text fields: one for userLastName and one for userFirstName. When we submit a form, those input names we send a request to the browser that has a request string, a post request in our case, with each input name and their value. After we submit the form, PHP can now access that string with $_POST, which is an array of variables with key values being those input names. If we want a particular variable, we can just call $_POST[‘userLastName’] and that would get us the value of whatever the user put in that user input. We already worked with arrays, which means you understand understand how to print out the entire array using print_r(array). You can do the same thing with the post value array. What if we want to do something other than spitting out the data?
As you can see when a user types in a number and hits submit, the number is multiplied by 7. Or if the user is a wise guy, and types in a another character it returns “Not a Number!!!” because it wasn’t actually a number. Ok, it doesn’t actually do that, but I will show you how to make it do that in the section below about server side validation. In the error handling tutorial, you will learn even better ways to handle this in a more appropriate manner.
Server Side Validation
Another variable that I haven’t mentioned is a catchall variable. The $_REQUEST variable does not care about how the information was transferred. This is useful for situations where you might have a GET and a POST for the same variable. For instance, maybe someone needs to comment on a certain article and would get to that page through a link. But once they arrive at the comment form, they need to post the comment. So, you would need a GET variable for when they arrive, but a POST variable when they post. However, you should not use the request variable unless it is a situation similar to this one. It is just bad practice. Know your variables.