PHP Forms

The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

PHP $_GET Function

The built-in $_GET function is used to collect values in a form with method=”get”.

Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser’s address bar) and has limits on the amount of information to send.

<form action="test.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

When the user clicks the “Submit” button, the URL sent to the server could look something like this:

http://learnwebdevelopment.info/test.php?fname=Test&age=25

The “test.php” file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array):

<?php
//test.php

echo $_GET['fname']; echo "<br>";
echo $_GET['age'];
?>

PHP $_POST Function

The built-in $_POST function is used to collect values from a form sent with method=”post”.

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

<form action="test.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

When the user clicks the “Submit” button, the URL will look like this:

http://learnwebdevelopment.info/test.php

The “test.php” file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array):

<?php
//test.php

echo $_POST['fname']; echo "<br>";
echo $_POST['age'];
?>

Posted in Php