Handling HTML Forms with PHP
How HTML Forms Work
All Web forms start with an opening <
form > tag, and end with a closing < /form > tag:
< form action=”myscript.php”
method=”post” >
< !-- Contents of the form go here --
>
< /form >
There are two attributes within the opening
<form> tag:
action tells the Web browser where to send
the form data when the user fills out and submits the form. This should either
be an absolute URL (such as http://www.example.com/myscript.php ) or a relative
URL (such as myscript.php , /myscript.php , or ../scripts/myscript.php ).
method tells the browser how to send the form data. You can use two methods: get is useful for sending small amounts of data and makes it easy for the user to resubmit the form, and post can send much larger amounts of form data.
Various Form Controlles:
A text input field –– This allows the
user to enter a single line of text.
<label for=”textField”>A text input
field</label>
<input type=”text” name=”textField”
id=”textField” value=”” />
A password field — This works like
a text input field, except that the entered text is not displayed. This is, of
course, intended for entering sensitive information such as passwords.
<label for=”passwordField”>A password
field</label>
<input type=”password” name=”passwordField”
id=”passwordField” value=”” />
checkbox field — This is a simple
toggle; it can be either on or off. The value attribute should
contain the value that will be sent to the
server when the checkbox is selected (if the checkbox
isn’t selected, nothing is sent):
<label for=”checkboxField”>A checkbox
field</label>
<input type=”checkbox”
name=”checkboxField” id=”checkboxField” value=”yes” />
Radio button fields — Radio buttons
tend to be placed into groups of at least two buttons.
All buttons in a group have the same name
attribute. Only one button can be selected per group. As with checkboxes, use
the value attribute to store the value that is sent to the server if the button
is selected. Note that the value attribute is mandatory for checkboxes and
radio buttons, and optional for other field types:
<label for=”radioButtonField1”>A
radio button field</label>
<input type=”radio”
name=”radioButtonField” id=”radioButtonField1” value=”radio1” />
<label
for=”radioButtonField2”>Another radio button</label>
<input type=”radio”
name=”radioButtonField” id=”radioButtonField2” value=”radio2” />
A submit button — Clicking this type of button sends the filled-in form to the server-side script for processing. The value attribute stores the text label that is displayed inside the button (this value is also sent to the server when the button is clicked):
<label for=”submitButton”>A submit
button</label>
<input type=”submit” name=”submitButton”
id=”submitButton” value=”Submit Form” />
A reset button — This type of
button resets all form fields back to their initial values (often
empty). The value attribute contains the
button label text:
<label for=”resetButton”>A reset
button</label>
<input type=”reset” name=”resetButton”
id=”resetButton” value=”Reset Form” />
A file select field — This allows the
users to choose a file on their hard drive for uploading to the server. The
value attribute is usually ignored by the browser:
<input type=”file” name=”fileSelectField”
id=”fileSelectField” value=”” />
A hidden field — This type of
field is not displayed on the page; it simply stores the text value
specified in the value attribute. Hidden
fields are great for passing additional information from
the form to the server.
<label for=”hiddenField”>A hidden
field</label>
<input type=”hidden” name=”hiddenField”
id=”hiddenField” value=”” />
An image field — This works like a submit button, but allows you to use your own button graphic instead of the standard gray button. You specify the URL of the button graphic using the src attribute, and the graphic’s width and height (in pixels) with the width and height attributes. As with the submit button, the value attribute contains the value that is sent to the server when the button is clicked:
<label for=”imageField”>An image
field</label>
<input type=”image” name=”imageField”
id=”imageField” value=”” src=”asterisk.gif” width=”23” height=”23” />
A push button — This type of button doesn’t do anything by default when it’s clicked, but you can make such buttons trigger various events in the browser using JavaScript. The value attribute specifies the text label to display in the button:
<label for=”pushButton”>A push
button</label>
<input type=”button” name=”pushButton”
id=”pushButton” value=”Click Me” />
A pull-down menu — This allows a user
to pick a single item from a predefined list of options.
<label for=”pullDownMenu”>A pull-down
menu</label>
<select name=”pullDownMenu”
id=”pullDownMenu” size=”1”>
<option value=”option1”>Option
1</option>
<option value=”option2”>Option
2</option>
<option value=”option3”>Option
3</option>
</select>
A list box — This works just
like a pull-down menu, except that it displays several options at
once. To turn a pull-down menu into a list
box, change the size attribute from 1 to the number
of options to display at once:
<label for=”listBox”>A list
box</label>
<select name=”listBox” id=”listBox”
size=”3”>
<option value=”option1”>Option
1</option>
<option value=”option2”>Option
2</option>
<option value=”option3”>Option
3</option>
</select>
A multi-select list box — This works like a list box, but it also allows the user to select multiple items at once by holding down Ctrl (on Windows and Linux browsers) or Command (on Mac browsers).
<label for=”multiListBox”>A
multi-select list box</label>
<select name=”multiListBox”
id=”multiListBox” size=”3” multiple=”multiple”>
<option value=”option1”>Option
1</option>
<option value=”option2”>Option
2</option>
<option value=”option3”>Option
3</option>
</select>
You can preselect an option in any type of
select element by adding the attribute
selected=”selected” to the relevant
<option> tag — for example: <option value=”option1”
selected=”selected”>.
A text area field — This is similar to
a text input field, but it allows the user to enter multiple
lines of text.
<label for=”textAreaField”>A text
area field</label>
<textarea name=”textAreaField”
id=”textAreaField” rows=”4” cols=”50”></textarea>
Capturing Form Data with PHP
Introduction
First of all, the form's action attribute
needs to contain the URL of the PHP script that will handle the form.
For example:
<form
action="form_handler.php"method="post">
When users send their forms, their data is
sent to the server and the form_handler.php script is run. The script then
needs to read the form data and act on it.
Superglobal Array |
Description |
$_GET |
Contains a list of all the field names and
values sent by a form using the get method |
$_POST |
Contains a list of all the field names and
values sent by a form using the post method |
$_REQUEST |
Contains the values of both the $_GET and
$_POST arrays combined, along with the values of the $_COOKIE superglobal
array |
Each of these three superglobal arrays
contains the field names from the sent form as array keys, with the field
values themselves as array values.
For example, suppose you created a form
using the get method, and that form contained the following control:
<input type="text" name="emailAddress" value=" "/>
You could then access the value that the
user entered into that form field using either the $_GET or the $_REQUEST
superglobal:
$email = $_GET["emailAddress"];
$email =
$_REQUEST["emailAddress"];
Example
In this example, you create a simple user
registration form, then write a form handler script that reads the field values
sent from the form and displays them in the page.
First, create the registration form.
Save the following HTML code as
registration.html in your document root folder:
<html
xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>Membership Form</title>
<link rel=”stylesheet” type=”text/css” href=”common.css” />
</head>
<body>
<h1>Membership Form</h1>
<p>Thanks for choosing , please fill in
your details below and click Send Details.</p>
<form action=”process_registration.php”
method=”post”>
<div style=”width: 30em;”>
<label for=”firstName”>First
name</label>
<input type=”text” name=”firstName”
id=”firstName” value=”” />
<label for=”lastName”>Last
name</label>
<input type=”text” name=”lastName”
id=”lastName” value=”” />
<label for=”password1”>Choose a
password</label>
<input type=”password” name=”password1”
id=”password1” value=”” />
<label for=”password2”>Retype
password</label>
<input type=”password” name=”password2”
id=”password2” value=”” />
<label for=”genderMale”>Are you
male...</label>
<input type=”radio” name=”gender”
id=”genderMale” value=”M” />
<label for=”genderFemale”>...or
female?</label>
<input type=”radio” name=”gender” id=”genderFemale”
value=”F” />
<label for=”favoriteWidget”>What’s
your favorite widget?</label>
<select name=”favoriteWidget”
id=”favoriteWidget” size=”1”>
<option value=”superWidget”>The
SuperWidget</option>
<option value=”megaWidget”>The
MegaWidget</option>
<option value=”wonderWidget”>The
WonderWidget</option>
</select>
<label for=”newsletter”>Do you want
to receive our newsletter?</label>
<input type=”checkbox” name=”newsletter”
id=”newsletter” value=”yes”/>
<label for=”comments”>Any
comments?</label>
<textarea name=”comments” id=”comments”
rows=”4” cols=”50”> </textarea>
<div style=”clear: both;”>
<input type=”submit” name=”submitButton”
id=”submitButton”
value=”Send Details” />
<input type=”reset” name=”resetButton”
id=”resetButton”
value=”Reset Form” style=”margin-right:
20px;”/>
</div>
</form>
</body>
</html>
Next, save the following script as
process_registration.php in your document root, the folder where you placed
registration.html.
<html>
<head>
<title>Thank You</title>
</head>
<body>
Thank You
<p>Thank you for registering. Here is the information you
submitted:</p>
<dl>
<dt>First name</dt><dd><?php echo
$_POST["firstName"]?></dd>
<dt>Last name</dt><dd><?php echo
$_POST["lastName"]?></dd>
<dt>Password</dt><dd><?php echo
$_POST["password1"]?></dd>
<dt>Retyped password</dt><dd><?php echo
$_POST["password2"]?></dd>
<dt>Gender</dt><dd><?php echo
$_POST["gender"]?></dd>
<dt>Favorite widget</dt><dd><?php echo
$_POST["favoriteWidget"]?></dd>
<dt>Do you want to receive our newsletter?</dt><dd>
<?php echo
$_POST["newsletter"]?></dd>
<dt>Comments</dt><dd><?php echo
$_POST["comments"]?></dd>
</dl>
</body>
</html>
Fill in the fields in the form, then click
the Send Details button.
If all goes well, you should see a page
displaying the data that you just entered.
Dealing Securely with Form Data
First of all, you wouldn ’ t of course
display the password that the users had just entered (although you might send
them their password in an email to remind them of it).
Secondly, it ’ s generally a bad idea to
pass any user - entered data — such as the values in $_GET and $_POST —
straight through to a statement like echo() or print() for displaying in a Web
page.
Handling Empty Form Fields
However, users often forget to (or don ’ t
want to) fill in certain fields in a form. When this happens, some data is not
sent to the server. Sometimes the field is sent as an empty string; sometimes
no field name is sent at all. The following table illustrates the behavior of
various form controls when they ’ re not filled in or selected:
Dealing with Multi - Value Fields
For example, the following form fields are
capable of sending multiple values to the server:
<label for=”favoriteWidgets”>What are
your favorite widgets?</label>
<select name=”favoriteWidgets”
id=”favoriteWidgets” size=”3” multiple=”multiple”>
<option value=”superWidget”>The
SuperWidget</option>
<option value=”megaWidget”>The
MegaWidget</option>
<option value=”wonderWidget”>The
WonderWidget</option>
</select>
<label for=”newsletterWidgetTimes”>
Do you want to receive our ‘Widget Times’
newsletter?</label>
<input type=”checkbox” name=”newsletter”
id=”newsletterWidgetTimes” value=”widgetTimes” />
<label
for=”newsletterFunWithWidgets”>
Do you want to receive our ‘Fun with
Widgets’ newsletter?</label>
<input type=”checkbox” name=”newsletter”
id=”newsletterFunWithWidgets” value=”funWithWidgets” />
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. Then, when the 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=”favoriteWidgets[]”
id=”favoriteWidgets” size=”3” multiple=”multiple” ... </select>
You ’ d then retrieve the array containing
the submitted field values as follows:
$favoriteWidgetValuesArray = $_GET[“favoriteWidgets”];
// If using get method
$favoriteWidgetValuesArray =
$_POST[“favoriteWidgets”]; //
If using post method
Storing PHP Variables in Forms
A hidden field is a special type of input
element that can store and send a string value, just like a regular text input
control. A hidden field is not displayed on the page although its value can be
seen by viewing the page source. Its value cannot be changed by the users when
they're filling out the form. By using hidden fields, you can store data between
one browser request and the next:
<input type="hidden" name="selectedWidget"
value="<?php echo $selectedWidget ?> " />
Do not use hidden fields to transmit
sensitive or critical information such as user IDs or order numbers.
Example
<form action="registration_multistep.php"
method="post">
<div style="width: 30em;">
<input type="hidden"
name="step" value="1" />
<input type="hidden"
name="gender" value="<?php setValue(" gender" )
?>" />
<input type="hidden"
name="favoriteWidget" value="<?php setValue("
favoriteWidget" ) ?>"/> <input type="hidden"
name="newsletter" value="<?php setValue("
newsletter" ) ?>" />
<input type="hidden"
name="comments" value="<?php setValue(" comments" )
?>" />
<label
for="firstName">First name</label>
<input type="text"
name="firstName" id="firstName" value="<?php
setValue("firstName") ?>"/>
<label for="lastName">Last
name</label>
<input type="text"
name="lastName" id="lastName" value=" <?php
setValue("lastName") ?>"/>
<div style="clear: both;">
<input type="submit"
name="submitButton" id="nextButton" value= " Next
>"/>
</div>
</div>
</form>
Creating File Upload Forms
PHP allows you to upload single and
multiple files through few lines of code only.
PHP file upload features allow you to
upload binary and text files both. Moreover, you can have the full control over
the file to be uploaded through PHP authentication and file operation
functions.
PHP $_FILES
The PHP global $_FILES contains all the information
of file. By the help of $_FILES global, we can get file name, file type, file
size, temp file name and errors associated with file.
Here, we are assuming that file name is filename.
$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in
bytes).
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the
server.
$_FILES['filename']['error']
Returns error code
associated with this file.
move_uploaded_file() function
The move_uploaded_file() function moves the
uploaded file to a new location. The move_uploaded_file() function checks
internally if the file is uploaded thorough the POST request. It moves the file
if it is uploaded through the POST request.
Syntax
bool move_uploaded_file ( string $filename
, string $destination )
Example:
<?php
$target_path = "e:/";
$target_path = $target_path.basename(
$_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'],
$target_path))
{
echo "File uploaded
successfully!";
}
Else
{
echo "Sorry, file not uploaded, please
try again!";
}
?>
***
Redirecting After a Form Submission
Redirection is done by outputting a
Location using PHP using the header() function. Here's how to redirect to a
page called thanks.html: header( "Location: thanks.html" ); Don't
output any content to the browser via echo() or print(), or by including HTML
markup outside the <?php ... ?> tags before calling header().
<?php
if ( isset( $_POST["submitButton"] ) )
{
// (deal with the submitted fields here)
header( "Location: thanks.html" );
exit;
} else {
displayForm();
}
function displayForm()
{
?>
<!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="lastName">Last
name</label>
<input type="text" name="lastName"
id="lastName" value="" />
<input type="submit" name="submitButton" id="submitButton"
value= "Send Details" />
</form>
</body>
</html>
<?php
}
?>
No comments:
Post a Comment