In this brief article, we will see how to work with forms and inputs in PHP.
Using HTML forms, you can pass parameters to the PHP back-end. Let us examine the following form:
<form action=’’> <input type=’text’ name=’name’> <input type=’submit’ name=’submit’ value=’Submit’> </form>
Now, this form will perform a GET submission. In PHP, you can get the text input with the following code:
If (array_key_exists(“name”, $_GET)) { // do something with $_GET[‘name’] }
Should the form be using a POST request method
<form method=’post’ action=’’> <input type=’text’ name=’name’> <input type=’submit’ name=’submit’ value=’Submit’> </form>
Now, the difference is that the form above uses POST for submission. A major difference between GET and POST is that GET submits the parameters as part of the URL. The previous submission would have looked like this with GET: page.com?name=someName&submit=Submit. An obvious drawback with such submission is that it would stay within the browser’s history, it can be bookmarked and shared which is totally not a good idea when the data ought not to be shared. Therefore, for data which is not meant to be shared publicly and data that is private or sensitive always use POST.
In PHP, you can get the name input from a POST submission by using the $_POST superglobal instead of $_GET:
If (array_key_exists(“name”, $_POST)) { // do something with $_POST[‘name’] }
It is also possible to expect both POST and GET submissions with the same inputs; or allow both for an API, etc. In such a case, you can simply check the $_REQUEST superglobal for the desired input, and if the input exists from a POST or a GET submission, it will be available in the $_REQUEST superglobal.
If (array_key_exists(“name”, $_REQUEST)) { // do something with $_REQUEST[‘name’] }
There are also PUT and DELETE request methods with the HTTP protocol but they are not typically used with forms yet. You may still rely on it when using APIs though. DELETE is used when you want to delete some form of a record and PUT is used when you want to put some file or a record at a specific URL.
Finally, the form could submit to any/arbitrary URL, where you could check the $_GET, $_POST, or $_REQUEST superglobals for inputs.
<form action=’myscript.php’> <input type=’text’ name=’name’> <input type=’submit’ name=’submit’ value=’Submit’> </form>
In the case above, we should have a file called myscript.php in which we check for the inputs.
Leave a Reply