SlideShare a Scribd company logo
1 of 42
Chapter 6
Getting Data from the Client
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.
2
Introduction (cont…)
• Handling forms is a multipart process.
• The creation of a form into which a user can enter the
required details.
• 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
reentering, 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.
3
Introduction (cont…)
• Form controls include text fields, password fields, hidden field,
radio buttons, checkboxes, textarea fields, drop-down menus,
listbox, file uploads, submit button, image button, reset button,
button field, color, 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 controls.
The destination URL to which the form data is to be
submitted.
4
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.
5
Retrieving Submitted Data
• To collect form data, we use PHP superglobals with control
name as index (associative array):
• $_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.
6
Example (textbox and password)
<form method="post">
Full name: <input type="text" name="name">
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 ['name']);
echo ("<br>Password: " . $_POST ['pword']);
?>
7
Where name and pword are control’s names.
Important notes
• Superglobals are in uppercase letters.
• You can use single or double quotes with superglobals
indexes.
• Form control names are case sensitive.
8
Textbox, password, and textarea
<form method="post">
<input type="text" name="fullName"><br>
<input type="password" name="pinCode"><br>
<textarea name="comment" cols="30" rows="6"></texta
rea><br>
<input type="reset" value="Reset form">
<input type="submit" name="submit" value="Register">
</form>
9
PHP Code
<?php
echo ("User name: " . $_POST ['fullName']);
echo ("<br>Password: " . $_POST ['pinCode']);
echo ("<br>Comment: ") . $_POST ['comment']);
?>
10
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>
<?php
if (!empty($_POST['sex']))
echo ("<br>sex: " . $_POST['sex']);
?>
11
checkbox fields (html code)
<form method="post">
<input type="checkbox" name="faculties[]" value="engineering">Engin
eering
<input type="checkbox" name="faculties[]" value="medicine">
Medicine
<input type="checkbox" name="faculties[]" value="computer sci
ences">Computer Sciences
<input type="submit" name="submit" value="Register">
</form>
12
checkbox fields (php code)
<?php
foreach ($_POST['faculties'] as $f)
echo ("$f, ");
?>
13
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="Marko">Marko</option>
</select> <br>
<input type="submit" name="submit" value="Register">
</form>
14
Drop-down menu (php code)
<?php
if (!empty($_POST['pob']))
echo ("<br>Place of birth: ". $_POST['pob']);
?>
15
Listbox (multiple choice)
<form method="post" enctype="multipart/form-data">
<select name="residence[]" multiple>
<option value="Muqdisho">Muqdisho</option>
<option value="Hargeysa">Hargeysa</option>
<option value="Kismayo">Kismayo</option>
<option value="Marko">Marko</option>
</select> <br>
<input type="submit" name="submit" value="Register">
</form>
16
Listbox (multiple choice)
<?php
if (!empty($_POST['residence'])) {
foreach ($_POST['residence'] as $r)
echo ("$r, ");
}
?>
17
Upload Files in PHP
18
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).
19
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:xampptmp" is default).
upload_tmp_dir = "C:xampptmp"
• Maximum allowed size for uploaded files (40MB is default).
upload_max_filesize = 40M
20
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
21
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
N.B. After configuring php_ini file, you should restart the
server.
22
Temporary Directory
• Also final storage directory must exist with the correct
permissions. Initially files are uploaded into a temporary
directory ("C:xampptmp") and then relocated to a target
destination by a PHP script.
• Information in the phpinfo.php page describes the default
configurations of XAMPP server.
23
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.
24
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>
• Notice the addition of enctype = "multipart/form-data" in the form
attributes.
25
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.
26
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.
27
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.
28
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.
29
Example
$_FILES['scertificate']['name'];
$_FILES['scertificate']['size'];
$_FILES['scertificate']['tmp_name'];
$_FILES['scertificate']['type'];
30
Move file
• 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.
31
Example PHP Code
<?php
if (move_uploaded_file($_FILES['scertificate']['tmp_name'], "D
ocs/". $_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.
32
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.");
In this example, the uploaded file will be named as full name
of the user.
33
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.");
34
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.");
35
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 ("docx", "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");
36
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.
37
Example
HTML code:
<form method="post" enctype="multipart/form-data">
<input type="file" name="myFiles[]" multiple>
<input type="submit" name="submit" value="Upload">
</form>
38
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");
?>
39
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
40
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
41
practice makes perfect
42

More Related Content

Similar to Chapter 6 Getting Data from the Client (1).pptx

Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5Mohd Harris Ahmad Jaal
 
Class 21
Class 21Class 21
Class 21Jiyeon Lee
 
Class 21
Class 21Class 21
Class 21Jiyeon Lee
 
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erickokelloerick
 
Web app development_php_07
Web app development_php_07Web app development_php_07
Web app development_php_07Hassen Poreya
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleKaty Slemon
 
Html forms
Html formsHtml forms
Html formseShikshak
 
forms.pptx
forms.pptxforms.pptx
forms.pptxasmabagersh
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validationMaitree Patel
 
05 File Handling Upload Mysql
05 File Handling Upload Mysql05 File Handling Upload Mysql
05 File Handling Upload MysqlGeshan Manandhar
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiNaveen Kumar Veligeti
 

Similar to Chapter 6 Getting Data from the Client (1).pptx (20)

Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5
 
PHP - Introduction to PHP Forms
PHP - Introduction to PHP FormsPHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
 
Class 21
Class 21Class 21
Class 21
 
Class 21
Class 21Class 21
Class 21
 
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erick
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Web app development_php_07
Web app development_php_07Web app development_php_07
Web app development_php_07
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
 
Cmsc 100 (web forms)
Cmsc 100 (web forms)Cmsc 100 (web forms)
Cmsc 100 (web forms)
 
Php BASIC
Php BASICPhp BASIC
Php BASIC
 
Html forms
Html formsHtml forms
Html forms
 
Html forms
Html formsHtml forms
Html forms
 
Html forms
Html formsHtml forms
Html forms
 
forms.pptx
forms.pptxforms.pptx
forms.pptx
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 
Php summary
Php summaryPhp summary
Php summary
 
05 File Handling Upload Mysql
05 File Handling Upload Mysql05 File Handling Upload Mysql
05 File Handling Upload Mysql
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligeti
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 

Chapter 6 Getting Data from the Client (1).pptx

  • 1. Chapter 6 Getting Data from the Client
  • 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. 2
  • 3. Introduction (cont…) • Handling forms is a multipart process. • The creation of a form into which a user can enter the required details. • 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 reentering, 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. 3
  • 4. Introduction (cont…) • Form controls include text fields, password fields, hidden field, radio buttons, checkboxes, textarea fields, drop-down menus, listbox, file uploads, submit button, image button, reset button, button field, color, 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 controls. The destination URL to which the form data is to be submitted. 4
  • 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. 5
  • 6. Retrieving Submitted Data • To collect form data, we use PHP superglobals with control name as index (associative array): • $_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. 6
  • 7. Example (textbox and password) <form method="post"> Full name: <input type="text" name="name"> 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 ['name']); echo ("<br>Password: " . $_POST ['pword']); ?> 7 Where name 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. 8
  • 9. Textbox, password, and textarea <form method="post"> <input type="text" name="fullName"><br> <input type="password" name="pinCode"><br> <textarea name="comment" cols="30" rows="6"></texta rea><br> <input type="reset" value="Reset form"> <input type="submit" name="submit" value="Register"> </form> 9
  • 10. PHP Code <?php echo ("User name: " . $_POST ['fullName']); echo ("<br>Password: " . $_POST ['pinCode']); echo ("<br>Comment: ") . $_POST ['comment']); ?> 10
  • 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> <?php if (!empty($_POST['sex'])) echo ("<br>sex: " . $_POST['sex']); ?> 11
  • 12. checkbox fields (html code) <form method="post"> <input type="checkbox" name="faculties[]" value="engineering">Engin eering <input type="checkbox" name="faculties[]" value="medicine"> Medicine <input type="checkbox" name="faculties[]" value="computer sci ences">Computer Sciences <input type="submit" name="submit" value="Register"> </form> 12
  • 13. checkbox fields (php code) <?php foreach ($_POST['faculties'] as $f) echo ("$f, "); ?> 13
  • 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="Marko">Marko</option> </select> <br> <input type="submit" name="submit" value="Register"> </form> 14
  • 15. Drop-down menu (php code) <?php if (!empty($_POST['pob'])) echo ("<br>Place of birth: ". $_POST['pob']); ?> 15
  • 16. Listbox (multiple choice) <form method="post" enctype="multipart/form-data"> <select name="residence[]" multiple> <option value="Muqdisho">Muqdisho</option> <option value="Hargeysa">Hargeysa</option> <option value="Kismayo">Kismayo</option> <option value="Marko">Marko</option> </select> <br> <input type="submit" name="submit" value="Register"> </form> 16
  • 17. Listbox (multiple choice) <?php if (!empty($_POST['residence'])) { foreach ($_POST['residence'] as $r) echo ("$r, "); } ?> 17
  • 18. Upload Files in PHP 18
  • 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). 19
  • 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:xampptmp" is default). upload_tmp_dir = "C:xampptmp" • Maximum allowed size for uploaded files (40MB is default). upload_max_filesize = 40M 20
  • 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 21
  • 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 N.B. After configuring php_ini file, you should restart the server. 22
  • 23. Temporary Directory • Also final storage directory must exist with the correct permissions. Initially files are uploaded into a temporary directory ("C:xampptmp") and then relocated to a target destination by a PHP script. • Information in the phpinfo.php page describes the default configurations of XAMPP server. 23
  • 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. 24
  • 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> • Notice the addition of enctype = "multipart/form-data" in the form attributes. 25
  • 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. 26
  • 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. 27
  • 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. 28
  • 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. 29
  • 31. Move file • 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. 31
  • 32. Example PHP Code <?php if (move_uploaded_file($_FILES['scertificate']['tmp_name'], "D ocs/". $_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. 32
  • 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."); In this example, the uploaded file will be named as full name of the user. 33
  • 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."); 34
  • 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."); 35
  • 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 ("docx", "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"); 36
  • 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. 37
  • 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> 38
  • 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"); ?> 39
  • 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 40
  • 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 41