An Introduction to PHP

Form Data

When an HTML document has a form, the action attribute specifies the name of the program to handle the form data. When a PHP document is specified in the action attribute, the PHP document has access to the named fields in the form. Each field is accessible from the PHP arrays $_POST or $_GET. The variable chosen will depend on whether the form's method attribute was get or post.

The following example uses a form to get the user's name and age. The information is then displayed with a PHP document.

simpleForm.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>User Details</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>User Details</h1>
<form id="userDetails" name="userDetails" method="post" action="welcome.php">
<p>
    Enter your Name: <br>
    <input type="text" size="40" value="" name="name"><br>
    Enter your Age: <br>
    <input type="text" size="5" value="" name="age"><br>
    <input type="submit" value="Enter" name="welcome">
</p>
</form>
</body>
</html>

The following is the PHP script that is called from, simpleForm.html.

welcome.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Welcome</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    print "Welcome " . $_POST["name"] . "<br>";
    print "I see you are " . $_POST["age"] . " years old! <br>";
?>
</p>
</body>
</html>

Iterating through a Form collection

You may iterate through the form collection, using either of the server variables, $_GET, and $_POST. The following example uses $_POST variable to iterate through the form shown above.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Form Collection</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
    print "Posted variables: <br>";
    reset ($_POST);
    while(list($key,$val) = each ($_POST))
        print $key . " = " . $value . "<br>";
?>
</p>
</body>
</html>

You might also like...

Comments

About the author

Gez Lemon United Kingdom

I'm available for contract work. Please visit Juicify for details.

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.” - E. W. Dijkstra