Q:
Explain when to use GET or POST. Provide example for both the ways.
Answer
Both GET and POST are used to collect data from a form. However, when security is desired $_POST should be used. When the $_ POST variable is used, all variables used are NOT displayed in the URL. Also, they have no restrictions to the length of the variables. GET should be used when the interaction with the form is more like a question. For e.g. firing a query etc. POST should be used more often when the interaction is more like an order or the interaction changes the state of the resource.
POST example:
<form action="sample.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
On clicking submit the URL resembles to: https://www.mysamplesite.com/sample.php
The sample.php file can be used for catching the form data using $_POST
Hello <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old!
GET EXAMPLE
<form action="sample.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
On clicking submit the URL resembles to : https://www.mysamplesite.com/sample.php?name=jim&age=37
The sample.php file can be used for catching the form data using $_GET
Hello <?php echo $_GET["name"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
View answer
Workspace
Report Error
Discuss