RCRAMER.COM
Clever website slogan
Home > Tech > PHP

PHP Forms and User Input

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

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

The $_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 a POST method is invisible to others and has an 8 Mb maximum size limit by default (can be changed by setting the max_post_size in the php.ini file).

The example below contains an HTML form with two input fields and a submit button:

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

When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "hello.php". "hello.php" looks like this:

<html>
<body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body>
</html>

When to use 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. However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The $_GET Function

The built-in $_GET function is used to collect values from a form sent 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.

Example

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

When the user clicks on the "submit" button, the URL might look something like this:

http://www.mydomain.com/hello.php?fnam=bob&age=30 Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!

When to use method="get"?

When using method="get" in HTML forms, all variable names and values are displayed in the URL. This may be useful becuase it makes it possible to bookmark some pages.

This method should not be used when sending passwords or other sensitive information ans should not be used with values exceeding 2000 characters.

The $_REQUEST Function

The built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE.

The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.

Welcome <?php echo $_REQUEST["fname"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!