Chapter 6 Getting Data From The Client (Form Handling)
Chapter 6 Getting Data From The Client (Form Handling)
Chapter 6 Getting Data From The Client (Form Handling)
2
Introduction
• The main way that website users interact with PHP and
MySQL is using HTML forms.
• A form is a collection of controls (fields) used to gather
information from users.
• A form is made up of a collection of input controls.
• You use <FORM> tag to enter form to your web page and it
has closing tag </FORM>.
• All other tags are sub tags for <FORM> tag.
3
Introduction (cont…)
• Handling forms is a multipart process.
• The creation of a form into which a user can enter the
required data.
• The data is then sent to the web server, where it is
interpreted, often with some error checking.
• If the PHP code identifies one or more fields that require re-
entering, the form may be redisplayed with an error
message.
• When the code is satisfied with the accuracy of the input, it
takes some action that usually involves the database.
4
Introduction (cont…)
• Form controls include text fields, password fields, radio
buttons, checkboxes, textarea fields, drop-down menus,
listboxes, file uploads, submit button, reset button, button
field, date, time, email, number, range, search, tel, etc.
• To build a form, you must have at least the following elements:
⮚An opening <form> and closing </form> tag.
⮚A submission type specifying either a GET or POST method
⮚One or more input fields (controls) as well as submit button.
⮚The destination URL to which the form data is to be
submitted.
5
Form Elements (tags)
• <FORM>
• <FIELDSET> used to group related data in a form.
• <LEGEND> defines a caption for the <FIELDSET> element.
• <LABEL> defines a label for form elements. useful for screen-reader
users, because the screen-reader will read out loud the label when
the user focus on the input element.
• <INPUT> can be displayed in several ways, depending on the type
attribute.
• <SELECT> defines a drop-down list.
❖<OPTION> (it is a sub tag for <SELECT> tag) defines an option
that can be selected.
• <TEXTAREA> defines a multi-line input field.
6
Retrieving Submitted Data
• To collect form data, we use PHP superglobals (associative
array) with control’s name as index.
• $_GET: if form method is set to get.
• $_POST: if form method is set to post.
• $_REQUEST: if form method is set to either get or post.
• $_FILES: is used with upload file to collect file info.
7
Example (textbox and password)
<form method="post">
Full name: <input type="text" name="fullName">
Password: <input type="password" name="pword">
<input type="reset" value="Reset form">
<input type="submit" name="submit" value="Register">
</form>
<?php
echo ("User name: " . $_POST ['fullName']);
echo ("<br>Password: " . $_POST ['pword']);
?>
Where fullName and pword are control’s names.
8
Important notes
• Superglobals are in uppercase letters.
• You can use single or double quotes with superglobals
indexes.
• Form control names are case sensitive.
9
Textbox, password, and textarea
<form method="post">
<input type="text" name="fullName"><br>
<input type="password" name="pword"><br>
<textarea name="comment" cols="30" rows="6"></
textarea><br>
<input type="submit" name="submit" value="Register">
</form>
10
PHP Code
<?php
echo ("User name: " . $_POST ['fullName']);
echo ("<br>Password: " . $_POST ['pword']);
echo ("<br>Comment: ") . $_POST ['comment']);
?>
11
Radio button fields
<form method="post">
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female">Female<br>
<input type="submit" name="submit" value="Register">
</form>
N.B. Group of radio buttons should be the same name.
<?php
echo ("<br>sex: " . $_POST['sex']);
?>
12
checkbox fields (html code)
<form method="post">
<input type="checkbox" name="faculties[]" value="engineering">Engin
eering
<input type="checkbox" name="faculties[]" value="medicine">M
edicine
<input type="checkbox" name="faculties[]" value="computer sci
ences">Computer Sciences
<input type="submit" name="submit" value="Register">
</form>
13
checkbox fields (php code)
<?php
foreach ($_POST['faculties'] as $f)
echo ("$f, ");
?>
14
Drop-down menu (single choice)
<form method="post">
<select name="pob">
<option value="Muqdisho">Muqdisho</option>
<option value="Hargeysa">Hargeysa</option>
<option value="Kismayo">Kismayo</option>
<option value="Burca">Burco</option>
</select> <br>
<input type="submit" name="submit" value="Register">
</form>
15
Drop-down menu (php code)
<?php
echo ("<br>Place of birth: ". $_POST['pob']);
?>
16
Listbox (multiple choice)
<form method="post">
<select name="residence[]" multiple>
<option value="Muqdisho">Muqdisho</option>
<option value="Hargeysa">Hargeysa</option>
<option value="Kismayo">Kismayo</option>
<option value="Burca">Burco</option>
</select> <br>
<input type="submit" name="submit" value="Register">
</form>
17
Listbox (multiple choice)
<?php
foreach ($_POST['residence'] as $r)
echo ("$r, ");
?>
18
Upload Files in PHP
19
Configuring The "php.ini" File
• There are several settings in PHP’s configuration file (php.ini)
that dictate how PHP handles uploads, specifically stating
how large of a file can be uploaded and where the upload
should temporarily be stored (you can browse php info file).
20
Php.ini file Configuration (1 – 3)
First, ensure that PHP is configured to allow file uploads and
check the following in your "php.ini".
• Whether to allow HTTP file uploads (On is default).
file_uploads = On
• Temporary directory for HTTP uploaded files ("C:\xampp\
tmp" is default).
upload_tmp_dir = "C:\xampp\tmp"
• Maximum allowed size for uploaded files (40MB is default).
upload_max_filesize = 40M
21
Php.ini file Configuration (2 – 3)
• Maximum number of files that can be uploaded via a single
request (20 files is default).
max_file_uploads = 20
• Maximum size of POST data that PHP will accept (40MB is
default).
post_max_size = 40M
• Maximum amount of time each script may spend parsing
request data (60 seconds is default).
max_input_time = 60
22
Php.ini file Configuration (3 – 3)
• Maximum amount of memory a script may consume (512MB
is default).
memory_limit = 512M
• Maximum execution time of each script, in seconds (120
seconds is default).
max_execution_time = 120
24
Create The HTML Form
Create an HTML form that allow users to choose the image file
they want to upload.
Some rules to follow for the HTML form above:
• Make sure that the form uses method="post"
• The form also needs the following attribute:
enctype = "multipart/form-data"
It specifies which content-type to use when submitting the
form.
Without the requirements above, the file upload will not
work.
25
HTML Code
<form method="post" enctype="multipart/form-data">
<label>Secondary certificate: </label>
<input type="file" name="scertificate">
<input type="submit" name="submit" value="Upload">
</form>
26
Process of uploading files (1 of 2)
• The user opens the page containing a HTML form featuring a
browse button and a submit button.
• The user clicks the browse button and selects a file to upload
from the local PC.
• The full path to the selected file appears in the text filed then
the user clicks the submit button.
• The selected file is sent to the temporary directory on the
server.
27
Process of uploading files (2 of 2)
• The PHP script that was specified as the form handler in the
form's action attribute checks that the file has arrived and
then copies the file into an intended directory.
• The PHP script confirms the success to the user.
28
File Type & Permissions
• As usual when writing files, it is necessary for both
temporary and final locations to have permissions set that
enable file writing. If either is set to be read-only then
process will fail.
• An uploaded file could be a text file or image file or any
document.
29
Create the Upload File PHP Script
• Use !empty with control name, ($_FILES['']), to make sure
some file is selected.
• $_FILES[' '] is an array with the file information.
• $_FILE[] can have second argument such as name, size,
tmp_name, and type where:
[name] is the name of the file.
[size] is the size of the file.
[tmp_name] is the temporary name in the tmp folder
where the file is uploaded before its final destination.
[type] is the type of the file.
30
Example
$_FILES['scertificate']['name'];
$_FILES['scertificate']['size'];
$_FILES['scertificate']['tmp_name'];
$_FILES['scertificate']['type'];
31
move_uploaded_file ( ) function
• To move the file from the temporary folder (tmp) to the final
destination in the server we will be using the
move_uploaded_file ( ) function.
• It takes two arguments, temporary file name, destination
folder name and the name of the file in the destination
folder of the server.
32
Example PHP Code
<?php
if (move_uploaded_file($_FILES['scertificate']
['tmp_name'], "Docs/". $_FILES['scertificate']['name']))
echo ("<br>Certificate has been uploaded successfully.");
?>
In this example, the file will be uploaded to the destination
folder without renaming it.
33
Rename Uploaded File
$ext = explode(".", $_FILES['scertificate']['name']);
$ext = end($ext);
if (move_uploaded_file($_FILES['scertificate']['tmp_name'], ("Docs/".
$_POST['fullName']). ".$ext"))
echo ("<br>Your photo has been uploaded successfully.");
34
file_exists ( ) function
• You can use file_exists ( ) function to check whether or not a
file exists in the directory.
• Syntax: file_exists (path and file name)
• Example:
if (file_exists ("Docs/". $_FILES['scertificate']['name']))
echo ("<br>Sorry, file: ". $_FILES['scertificate']['name']. " already exists.");
35
Check file size
• To check for size of file, we can use size property of control.
• For example:
if (!$_FILES['scertificate']['size'])
echo ("File: ". $_FILES['scertificate']['name']. " is too big.");
36
Limit file extensions
• To limit file extensions allowed in the upload process to
predefined list of extensions use explode, strtolower, end
and in_array functions as follows:
$extensions = array ("jpg", "pdf");
$name_ext = explode (".", $_FILES['scertificate']['name']);
$ext = strtolower(end ($name_ext));
if (!in_array ($ext, $extensions))
echo ("<br>File extenssion: $ext is not allowed");
37
Uploading multiple files
• It is also possible to upload multiple files simultaneously and
have the information organized automatically in arrays for
you.
• To do so, you need to use the same array submission syntax
in the HTML form as you do with multiple selects of
dropdown menu and checkboxes.
38
Example
HTML code:
<form method="post" enctype="multipart/form-data">
<input type="file" name="myFiles[]" multiple>
<input type="submit" name="submit" value="Upload">
</form>
39
PHP code
<?php
for ($i = 0; $i < count($_FILES['myFiles']['name']); $i++)
if (move_uploaded_file($_FILES['myFiles']['tmp_name']
[$i], "Docs/". $_FILES['myFiles']['name'][$i]))
echo ("<br>Files uploaded successfully");
?>
40
Form Validation Checklist (1-2)
• Controls validation
1) Isset (radio button, checkbox, and submit)
2) Empty (textbox, password, dropdown menu, listbox, and
textarea, file upload)
3) And with full stop (checkbox and listbox)
4) Sort checkbox & listbox.
5) Uppercase first latter (radio button, checkbox, dropdown
menu, listbox)
6) File extension
41
Form Validation Checklist (2-2)
• File upload validation
7) Size
8) Already exists
9) Uploaded file and name it as the username
10)Display image on the screen after upload
11)Upload multiple files
12)Keep form data after submit and use a button to clear
data
13)And many more
42
practice makes perfect
43