Processing Form Input

You want to use the same HTML page to create a form and then process the data entered into it.

Use the $_SERVER['REQUEST_METHOD'] variable to determine whether the request was submitted with the get or post method.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
<?php
// if the get method is used, display the form.
// if the post method is used process the form.
// $_SERVER['SCRIPT_NAME'] is the path to the current script
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
?>
<form action = "<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="post">
Enter first name
<input type="text" name="first_name" />
<input type="submit" value="Submit" />
</form>
<?php } else {
	echo 'Hello, '.$_POST['first_name'];
}
?>
</p>
</body>
</html>

View the effect


Forms | Introduction | Creating a Form | Superglobals | Processing Form Input | Required Fields | Numbers | Drop-Down Menus | Radio Buttons | Checkboxes | Periods in Their Names | Preventing Cross-Site Scripting | Stripping out Slashes | Redirecting the User | Server Information | Determining Browser Type | Sticky Forms
© 2008: Hann So
email: hso@voyager.deanza.edu