We use the predefined $_POST variable to collect values in a form with method=”post”. The information that is hold by POST method is hidden from user. Noone can see it like GET method in browser’s address bar. It has no limits on the amount of the information to send. If you want to send some important data such as password, there is no better method to use for your security.
Lets make an example : (I am gonna use the same example in my previous lesson with POST method)
Our main.php file should look like this. The only difference between this and previous example is that: here we used method=”post” instead of method=”get”.
Our main.php file look like that:
<html> <head></head> <body> <form action="welcome.php" method="post"> Username: <input type="text" name="username"/> Age: <input type="text" name="age"/> <input type="submit"/> </form> </body> </html>
Our welcome.php file should look like this: (The only difference between this and previous example is that: here we used $_POST instead of $_GET.)
Welcome <?php echo $_POST["username"]; ?>! </br>
You are <?php echo $_POST["age"]; ?> years old.
If we type Mehmet into username input field and 22 into age input field then click on the submit button we should see that output in welcome.php url location:
You are 22 years old.
And our browser’s address bar should look like this:
As you see all datas that we typed into input fields are carried invisible unlike GET method.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.
So, if we alter our welcome.php file like that:
Welcome <?php echo $_REQUEST["username"]; ?>! </br> You are <?php echo $_REQUEST["age"]; ?> years old.
We will be able to use our welcome.php file with either POST method or GET method of our main.php file.
In this lesson you’ve learned how to send data with POST method in PHP. Stay cool and stay connected to learn more! 😉