You are on page 1of 28

HTML Forms

HTML Forms are required, when you want to collect some data from the site
visitor. For example, during user registration you would like to collect
information such as name, email address, credit card, etc.

A form will take input from the site visitor and then will post it to a back-
end application such as CGI, ASP Script or PHP script etc. The back-end
application will perform required processing on the passed data based on
defined business logic inside the application.

There are various form elements available like text fields, textarea fields,
drop-down menus, radio buttons, checkboxes, etc.

The HTML <form> tag is used to create an HTML form and it has following


syntax −
<form action = "Script URL" method = "GET|POST">
form elements like input, textarea etc.
</form>

Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes −

Sr.No Attribute & Description

1 action

Backend script ready to process your passed data.

2
method

Method to be used to upload data. The most frequently used are GET and
POST methods.

3 target

Specify the target window or frame where the result of the script will be
displayed. It takes values like _blank, _self, _parent etc.

4
enctype
You can use the enctype attribute to specify how the browser encodes
the data before it sends it to the server. Possible values are −

application/x-www-form-urlencoded − This is the standard method


most forms use in simple scenarios.

mutlipart/form-data − This is used when you want to upload binary


data in the form of files like image, word file etc.

Note − You can refer to Perl & CGI for a detail on how form data upload
works.

HTML Form Controls


There are different types of form controls that you can use to collect data
using HTML form −

 Text Input Controls

 Checkboxes Controls

 Radio Box Controls

 Select Box Controls

 File Select boxes

 Hidden Controls

 Clickable Buttons

 Submit and Reset Button

Text Input Controls


There are three types of text input used on forms −

 Single-line text input controls − This control is used for items that require
only one line of user input, such as search boxes or names. They are created
using HTML <input> tag.
 Password input controls − This is also a single-line text input but it masks
the character as soon as a user enters it. They are also created using HTMl
<input> tag.

 Multi-line text input controls − This is used when the user is required to give
details that may be longer than a single sentence. Multi-line input controls are
created using HTML <textarea> tag.

Single-line text input controls


This control is used for items that require only one line of user input, such
as search boxes or names. They are created using HTML <input> tag.

Example
Here is a basic example of a single-line text input used to take first name
and last name −
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>Text Input Control</title>

</head>

<body>

<form >

First name: <input type = "text" name = "first_name" />

<br>

Last name: <input type = "text" name = "last_name" />

</form>

</body>
</html>

This will produce the following result −

Attributes
Following is the list of attributes for <input> tag for creating text field.

Sr.No Attribute & Description

1
type

Indicates the type of input control and for text input control it will be set
to text.

2 name

Used to give a name to the control which is sent to the server to be


recognized and get the value.

3
value

This can be used to provide an initial value inside the control.

4 size

Allows to specify the width of the text-input control in terms of


characters.

5
maxlength

Allows to specify the maximum number of characters a user can enter


into the text box.

Password input controls


This is also a single-line text input but it masks the character as soon as a
user enters it. They are also created using HTML <input>tag but type
attribute is set to password.

Example
Here is a basic example of a single-line password input used to take user
password −
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>Password Input Control</title>

</head>

<body>

<form >

User ID : <input type = "text" name = "user_id" />

<br>

Password: <input type = "password" name = "password" />

</form>

</body>

</html>

This will produce the following result −

Attributes
Following is the list of attributes for <input> tag for creating password field.

Sr.No Attribute & Description

1
type

Indicates the type of input control and for password input control it will
be set to password.
2
name

Used to give a name to the control which is sent to the server to be


recognized and get the value.

3 value

This can be used to provide an initial value inside the control.

4
size

Allows to specify the width of the text-input control in terms of


characters.

5 maxlength

Allows to specify the maximum number of characters a user can enter


into the text box.

Multiple-Line Text Input Controls


This is used when the user is required to give details that may be longer
than a single sentence. Multi-line input controls are created using HTML
<textarea> tag.

Example
Here is a basic example of a multi-line text input used to take item
description −
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>Multiple-Line Input Control</title>

</head>
<body>

<form>

Description : <br />

<textarea rows = "5" cols = "50" name = "description">

Enter description here...

</textarea>

</form>

</body>

</html>

This will produce the following result −

Attributes
Following is the list of attributes for <textarea> tag.

Sr.No Attribute & Description

1
name

Used to give a name to the control which is sent to the server to be


recognized and get the value.

2 rows

Indicates the number of rows of text area box.

3
cols

Indicates the number of columns of text area box

Checkbox Control
Checkboxes are used when more than one option is required to be selected.
They are also created using HTML <input> tag but type attribute is set
to checkbox..

Example
Here is an example HTML code for a form with two checkboxes −
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>Checkbox Control</title>

</head>

<body>

<form>

<input type = "checkbox" name = "maths" value = "on"> Maths

<input type = "checkbox" name = "physics" value = "on"> Physics

</form>

</body>

</html>

This will produce the following result −

Attributes
Following is the list of attributes for <checkbox> tag.

Sr.No Attribute & Description

1
type
Indicates the type of input control and for checkbox input control it will
be set to checkbox..

2 name

Used to give a name to the control which is sent to the server to be


recognized and get the value.

3
value

The value that will be used if the checkbox is selected.

4 checked

Set to checked if you want to select it by default.

Radio Button Control


Radio buttons are used when out of many options, just one option is
required to be selected. They are also created using HTML <input> tag but
type attribute is set to radio.

Example
Here is example HTML code for a form with two radio buttons −
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>Radio Box Control</title>

</head>

<body>

<form>
<input type = "radio" name = "subject" value = "maths"> Maths

<input type = "radio" name = "subject" value = "physics"> Physics

</form>

</body>

</html>

This will produce the following result −

Attributes
Following is the list of attributes for radio button.

Sr.No Attribute & Description

1 type

Indicates the type of input control and for checkbox input control it will
be set to radio.

2
name

Used to give a name to the control which is sent to the server to be


recognized and get the value.

3 value

The value that will be used if the radio box is selected.

4
checked

Set to checked if you want to select it by default.

Select Box Control


A select box, also called drop down box which provides option to list down
various options in the form of drop down list, from where a user can select
one or more options.
Example
Here is example HTML code for a form with one drop down box
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>Select Box Control</title>

</head>

<body>

<form>

<select name = "dropdown">

<option value = "Maths" selected>Maths</option>

<option value = "Physics">Physics</option>

</select>

</form>

</body>

</html>

This will produce the following result −

Attributes
Following is the list of important attributes of <select> tag −

Sr.No Attribute & Description

1
name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

2 size

This can be used to present a scrolling list box.

3
multiple

If set to "multiple" then allows a user to select multiple items from the
menu.

Following is the list of important attributes of <option> tag −

Sr.No Attribute & Description

1
value

The value that will be used if an option in the select box box is selected.

2 selected

Specifies that this option should be the initially selected value when the
page loads.

3
label

An alternative way of labeling options

File Upload Box


If you want to allow a user to upload a file to your web site, you will need to
use a file upload box, also known as a file select box. This is also created
using the <input> element but type attribute is set to file.

Example
Here is example HTML code for a form with one file upload box −
 Live Demo
<!DOCTYPE html>

<html>

<head>

<title>File Upload Box</title>

</head>

<body>

<form>

<input type = "file" name = "fileupload" accept = "image/*" />

</form>

</body>

</html>

This will produce the following result −

Attributes
Following is the list of important attributes of file upload box −

Sr.No Attribute & Description

1 name

Used to give a name to the control which is sent to the server to be


recognized and get the value.

2
accept

Specifies the types of files that the server accepts.

Button Controls
There are various ways in HTML to create clickable buttons. You can also
create a clickable button using <input>tag by setting its type attribute
to button. The type attribute can take the following values −

Sr.No Type & Description

1
submit

This creates a button that automatically submits a form.

2 reset

This creates a button that automatically resets form controls to their


initial values.

3
button

This creates a button that is used to trigger a client-side script when the
user clicks that button.

4 image

This creates a clickable button but we can use an image as background of


the button.

Example
Here is example HTML code for a form with three types of buttons −
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>File Upload Box</title>

</head>
<body>

<form>

<input type = "submit" name = "submit" value = "Submit" />

<input type = "reset" name = "reset" value = "Reset" />

<input type = "button" name = "ok" value = "OK" />

<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />

</form>

</body>

</html>

This will produce the following result −

Hidden Form Controls


Hidden form controls are used to hide data inside the page which later on
can be pushed to the server. This control hides inside the code and does not
appear on the actual page. For example, following hidden form is being
used to keep current page number. When a user will click next page then
the value of hidden control will be sent to the web server and there it will
decide which page will be displayed next based on the passed current page.

Example
Here is example HTML code to show the usage of hidden control −
 Live Demo

<!DOCTYPE html>

<html>

<head>

<title>File Upload Box</title>

</head>
<body>

<form>

<p>This is page 10</p>

<input type = "hidden" name = "pagename" value = "10" />

<input type = "submit" name = "submit" value = "Submit" />

<input type = "reset" name = "reset" value = "Reset" />

</form>

</body>

</html>

Multi Value Fields

Form fields can send multiple values, rather than a single value.

Example 1

For example, the following form fields are capable of sending multiple values to the
server:

<label for="mySelection">What are your favorite widgets?</label>


<select name="mySelection" id="mySelection" size="3" multiple="multiple">
<option value="PHP">PHP Language</option>
<option value="Java">Java Language</option>
<option value="CSS">CSS Language</option>
</select>

A multi-select list box, allowing the user to pick one or more (or no) options.

 Example 2
<label for="tested">Have you tested?</label>
<input type="checkbox" name="myTask" id="tested" value="testTask"/>
<label for="designed">Have you designed?</label>
<input type="checkbox" name="myTask" id="designed" value="designTask"/>

The checkboxes can have the same name (myTask) but different values (testTask
and designTask).
If the user checks both checkboxes then both values, testTask and designTask, are
sent to the server under the myTask field name.

How
So how can you handle multi-value fields in your PHP scripts? The trick is to add
square brackets ( [] ) after the field name in your HTML form.
When PHP engine sees a submitted form field name with square brackets at the
end, it creates a nested array of values within the $_GET or $_POST and
$_REQUEST superglobal array, rather than a single value.
You can then pull the individual values out of that nested array. So you might create
a multi-select list control as follows:

<select name="mySelection[]" id="mySelection"


size="3" multiple="multiple"> ... </select>

You'd then retrieve the array containing the submitted field values as follows:

$favoriteLanguage = $_GET["mySelection"]; // If using get method


$favoriteLanguage = $_POST["mySelection"]; // If using post method

Example 3

A Registration Form with Multi-Value Fields

<!DOCTYPE html5>
<html>
<body>
<form action="index.php" method="post">
<label for="firstName">First name</label>
<input type="text" name="firstName" id="firstName" value="" />

<label for="mySelection">What are your favorite widgets?</label>


<select name="mySelection[]" id="mySelection" size="3" multiple="multiple">
<option value="PHP">PHP Language</option>
<option value="Java">Java Language</option>
<option value="CSS">CSS Language</option>
</select>

<label for="tested">Choice One?</label>


<input type="checkbox" name="chioces[]" id="ChoiceOne" value="testTask" />

<label for="designed">Choice Two?</label>


<input type="checkbox" name="chioces[]" id="ChoiceTwo" value="designTask" />

<input type="submit" name="submitButton" id="submitButton" value="Send


Details" />
<input type="reset" name="resetButton" id="resetButton" value="Reset Form"/>
</div>
</form>

</body>
</html>

Now save the following script as index.php in your document root folder:

<!DOCTYPE html5>
<html>
<body>
<?php
$mySelection = "";
$chiocess = "";
if ( isset( $_POST["mySelection"] ) ) {
foreach ( $_POST["mySelection"] as $widget ) {
$mySelection .= $widget . ", ";
}
}
if ( isset( $_POST["chioces"] ) ) {
foreach ( $_POST["chioces"] as $chioces ) {
$chiocess .= $chioces . ", ";
}
}
$mySelection = preg_replace( "/, $/", "", $mySelection );
$chiocess = preg_replace( "/, $/", "", $chiocess );
?><dl>
<dt>First name</dt><dd><?php echo $_POST["firstName"]?></dd>
<dt>Favorite widgets</dt><dd><?php echo $mySelection?></dd>
<dt>You want to receive the following chiocess:</dt><dd>
<?php echo $chiocess?></dd>
<dt>Comments</dt><dd><?php echo $_POST["comments"]?></dd>
</dl>

</body>
</html>

What is the Form?


A Document that containing black fields, that the user can fill the data or
user can select the data. Casually the data will store in the data base

Example
Below example shows the form with some specific actions by using post
method.
<html>

<head>

<title>PHP Form Validation</title>

</head>

<body>

<?php
// define variables and set to empty values

$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = test_input($_POST["name"]);

$email = test_input($_POST["email"]);

$website = test_input($_POST["website"]);

$comment = test_input($_POST["comment"]);

$gender = test_input($_POST["gender"]);

function test_input($data) {

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

?>

<h2>Tutorials Point Absolute classes registration</h2>

<form method = "post" action = "/php/php_form_introduction.htm">

<table>

<tr>

<td>Name:</td>

<td><input type = "text" name = "name"></td>

</tr>

<tr>

<td>E-mail:</td>

<td><input type = "text" name = "email"></td>

</tr>

<tr>

<td>Specific Time:</td>
<td><input type = "text" name = "website"></td>

</tr>

<tr>

<td>Class details:</td>

<td><textarea name = "comment" rows = "5" cols = "40"></textarea></td>

</tr>

<tr>

<td>Gender:</td>

<td>

<input type = "radio" name = "gender" value = "female">Female

<input type = "radio" name = "gender" value = "male">Male

</td>

</tr>

<tr>

<td>

<input type = "submit" name = "submit" value = "Submit">

</td>

</tr>

</table>

</form>

<?php

echo "<h2>Your Given details are as :</h2>";

echo $name;

echo "<br>";

echo $email;

echo "<br>";

echo $website;

echo "<br>";

echo $comment;
echo "<br>";

echo $gender;

?>

</body>

</html>

It will produce the following result −

Storing Variables in Forms


There are two ways the browser client can send information to the web
server.

 The GET Method

 The POST Method


Before the browser sends the information, it encodes it using a scheme
called URL encoding. In this scheme, name/value pairs are joined with
equal signs and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with the + character and any other
nonalphanumeric characters are replaced with a hexadecimal values. After
the information is encoded it is sent to the server.

The GET Method


The GET method sends the encoded user information appended to the page
request. The page and the encoded information are separated by the ?
character.
http://www.test.com/index.htm?name1=value1&name2=value2

 The GET method produces a long string that appears in your server logs, in the browser's Location: box.

 The GET method is restricted to send upto 1024 characters only.

 Never use GET method if you have password or other sensitive information to be sent to the server.

 GET can't be used to send binary data, like images or word documents, to the server.

 The data sent by GET method can be accessed using QUERY_STRING environment variable.

 The PHP provides $_GET associative array to access all the sent information using GET method.

Try out following example by putting the source code in test.php script.
<?php

if( $_GET["name"] || $_GET["age"] ) {

echo "Welcome ". $_GET['name']. "<br />";

echo "You are ". $_GET['age']. " years old.";

exit();

?>

<html>

<body>

<form action = "<?php $_PHP_SELF ?>" method = "GET">

Name: <input type = "text" name = "name" />

Age: <input type = "text" name = "age" />

<input type = "submit" />

</form>
</body>

</html>

It will produce the following result −

The POST Method


The POST method transfers information via HTTP headers. The information
is encoded as described in case of GET method and put into a header called
QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.

 The POST method can be used to send ASCII as well as binary data.

 The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By
using Secure HTTP you can make sure that your information is secure.

 The PHP provides $_POST associative array to access all the sent information using POST method.

Try out following example by putting the source code in test.php script.
<?php

if( $_POST["name"] || $_POST["age"] ) {

if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {

die ("invalid name and name should be alpha");

echo "Welcome ". $_POST['name']. "<br />";

echo "You are ". $_POST['age']. " years old.";

exit();

?>

<html>

<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">

Name: <input type = "text" name = "name" />

Age: <input type = "text" name = "age" />

<input type = "submit" />


</form>

</body>

</html>

It will produce the following result −

The $_REQUEST variable


The PHP $_REQUEST variable contains the contents of both $_GET,
$_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will
explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data
sent with both the GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php

if( $_REQUEST["name"] || $_REQUEST["age"] ) {

echo "Welcome ". $_REQUEST['name']. "<br />";

echo "You are ". $_REQUEST['age']. " years old.";

exit();

?>

<html>

<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">

Name: <input type = "text" name = "name" />

Age: <input type = "text" name = "age" />

<input type = "submit" />

</form>

</body>

</html>

Here $_PHP_SELF variable contains the name of self script in which it is


being called.
It will produce the following result −

php - file create


php - creating confusion
In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this
conundrum.

In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call.
So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later).

php - how to create a file


The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that
we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).

Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we
are writing to the file, otherwise it will not create a new file.

PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist
and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.

1. $ourFileName = "testFile.txt";

Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.

2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

This bit of code actually has two parts. First we use the function fopenand give it two arguments: our file name and we inform PHP
that we want to write by passing the character "w".

Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file
handle into the $ourFileHandle variable. We will talk more about file handles later on.

3. fclose($ourFileHandle);

We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file
closing lesson.

php - permissions
If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file
access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command
called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.
In the near future Tizag.com will have a more in-depth tutorial on how to use CHMOD to set file permissions.

PHP header() Function

Definition and Usage

The header() function sends a raw HTTP header to a client.

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later,
you can use output buffering to solve this problem):

<html>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>

Syntax
header(string,replace,http_response_code)

Parameter Description

string Required. Specifies the header string to send

replace Optional. Indicates whether the header should replace previous or add a second header.
Default is TRUE (will replace). FALSE (allows multiple headers of the same type)

http_response_code Optional. Forces the HTTP response code to the specified value (available in PHP 4.3 and
higher)

Example 1
Prevent page caching:

<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>

...
...

Note: There are options that users may set to change the browser's default caching settings. By sending the
headers above, you should override any of those settings and force the browser to not cache!

Example 2
Let the user be prompted to save a generated PDF file (Content-Disposition header is used to supply a
recommended filename and force the browser to display the save dialog box):

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf


header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf


readfile("original.pdf");
?>

<html>
<body>

...
...

You might also like