Unit 4 - Creating and Validating Forms
Unit 4 - Creating and Validating Forms
UNIT – IV
CREATING AND VALIDATING
FORMS
E-mail: [email protected]
COURSE OUTCOMES (COS)
CO4 - Use form controls with validation to collect
user's input.
UO
Sunil P. Emekar
1. Use the relevant form controls to get user's input.
2. Design web pages using multiple Forms for the
given problem.
3. Apply the given validation rules on form.
4. Set/ modify/ delete cookies using cookies attributes.
5. Manage the given session using session variables.
2
FORMS
Input Element:
Sunil P. Emekar
5
HTTP BASICS
Sunil P. Emekar
from web servers and how the servers send the files
back.
The first line of an HTTP request looks like this:
GET /index.html HTTP/1.1
This line specifies an HTTP command, called a
method, followed by the address of a document and
the version of the HTTP protocol being used.
The two most common HTTP methods are GET and
POST.
6
GET VS. POST
The GET method is designed for retrieving
information, such as a document, an image, or the
results of a database query, from the server.
Sunil P. Emekar
The POST method is meant for posting information,
such as a credit card number or information that is to
be stored in a database, to the server.
This method displays the form values in the URL.
Sunil P. Emekar
it is possible to bookmark the page.
GET may be used for sending non-sensitive data.
When to use POST?
Information sent from a form with the POST method
is invisible to others (all names/values are embedded
within the body of the HTTP request)
has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as
support for multi-part binary input while uploading files
to server. 8
Sunil P. Emekar
$_GET
Contains any parameters that are part of a GET request, where
the keys of the array are the names of the form parameters
$_POST
Contains any parameters that are part of a POST request, where
the keys of the array are the names of the form parameters
$_FILES
Contains information about any uploaded files
$_SERVER
Contains useful information about the web server.
$_ENV 9
Contains the values of any environment variables, where the keys
of the array are the names of the environment variables
FORM CONTROLS
<input>
<button>
<select>
<textarea>
<option>
<INPUT>
The <input> tag specifies an input field where the
user can enter data.
The <input> element is the most important form
element.
The <input> element can be displayed in several
ways, depending on the type attribute.
The different input types are as follows:
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="submit">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="reset">
<input type="search">
<input type="time">
<input type="week">
BUTTON
The <button> element defines a clickable button
Syntax:
TextArea:
Example:
<textarea name="address" rows="3" cols="100">
Default Text Here
</textarea>
CHECKBOX & RADIO BUTTON
CheckBox:
Example:
<input type="checkbox" name="vehicle1" id="vehicle1">
I Have Bike
OR
Radio Button:
Example:
<input type="radio" id="male" name="gender" value="male”>
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender"
value="female">
<label for="female">Female</label><br>
OR
<input type="radio" id="male" name="gender"
value="male”> Male
<input type="radio" id="female" name="gender"
value="female"> Female
<SELECT>
The <select> element defines a drop-down list:
Example:
Sunil P. Emekar
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query
string
Sunil P. Emekar
$_SERVER['HTTP_ACCEPT_CHA Returns the Accept_Charset header from the current request
RSET'] (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable
because not all user-agents support it)
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the
current page 19
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the
current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to
communicate with the web server
$_SERVER['SCRIPT_FILENA Returns the absolute pathname of the currently
ME'] executing script
$_SERVER['SERVER_ADMIN' Returns the value given to the SERVER_ADMIN
] directive in the web server configuration file (if your
script runs on a virtual host, it will be the value defined
for that virtual host)
Sunil P. Emekar
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by
the web server for communication (such as 80)
$_SERVER['SERVER_SIGNAT Returns the server version and virtual host name which
URE'] are added to server-generated pages
$_SERVER['PATH_TRANSLA Returns the file system based path to the current script
TED']
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
20
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
WORKING WITH MULTIPLE FORMS
Sunil P. Emekar
2. A form Having multiple submit buttons
Since multiple submit buttons will invoke the same PHP
form processor, PHP script must be revised to "know"
which one was clicked so it can respond appropriately.
For this check name using if / case
21
WEB PAGE VALIDATION
Sunil P. Emekar
PHP. They are as follows −
Client-Side Validation − Validation is performed on
the client machine web browsers.
Server Side Validation − After submitted by data, The
data has sent to a server and perform validation checks
in server machine.
22
Empty String
The code below checks that the field is not empty. If
the user leaves the required field empty, it will show
an error message.
if (empty ($_POST["name"])) {
$errMsg = "Error! You didn't enter the Name.";
Sunil P. Emekar
echo $errMsg;
} else {
$name = $_POST["name"];
}
23
Validate String
$name = $_POST ["Name"];
if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
Sunil P. Emekar
}
Validate Number
$mobileno = $_POST ["Mobile_no"];
if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}
24
Validate Email
$email = $_POST ["Email"];
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-
]+)*(\.[a-z]{2,3})$^";
if (!preg_match ($pattern, $email) ){
$ErrMsg = "Email is not valid.";
echo $ErrMsg;
} else {
Sunil P. Emekar
echo "Your valid email address is: " .$email;
}
Input Length Validation
$mobileno = strlen ($_POST ["Mobile"]);
$length = strlen ($mobileno);
Sunil P. Emekar
browser.
Each time when client sends request to the server,
cookie is embedded with request. Such way, cookie can
be received at the server side.
26
CREATE COOKIES WITH PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, Security);
Only the name parameter is required. All other
Sunil P. Emekar
parameters are optional.
Name − This sets the name of the cookie. This variable is used
while accessing cookies.
Value − content that you actually want to store.
Sunil P. Emekar
Example
$value=$_COOKIE["CookieName"];//returns cookie value
28
DELETING COOKIE WITH PHP
Sunil P. Emekar
29
SESSIONS
A session is a way to store information (in variables) to
be used across multiple pages.
Unlike a cookie, the information is not stored on the
users computer.
Session variables hold information about one single
Sunil P. Emekar
user, and are available to all pages in one application.
By default, session variables last until the user closes
the browser or after a predetermined period of time i.e.
30 min
30
STARTING A PHP SESSION
A PHP session is easily started by making a call to
the session_start() function.
This function first checks if a session is already started
and if none is started then it starts one.
Sunil P. Emekar
It is recommended to put the call to session_start() at
the beginning of the page.
Session variables are stored in associative array
called $_SESSION[]. These variables can be accessed
during lifetime of a session.
PHP $_SESSION is an associative array that contains
all session variables. It is used to set and get session
variable values.
$_SESSION["user"] = "Sunil"; 31
GET PHP SESSION VARIABLE VALUES
Sunil P. Emekar
Example:
echo $_SESSION["user"];
32
DESTROYING A PHP SESSION
Sunil P. Emekar
single call can destroy all the session variables.
If you want to destroy a single session variable then
you can use unset() function to unset a session
variable.
Example:
33
SENDING EMAILS USING PHP
PHP mail() function is used to send email in PHP.
You can send text message, html message and
attachment with message using PHP mail() function.
Sunil P. Emekar
Syntax
bool mail(to,subject,message,headers,parameters);
Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email.
message Required. Defines the message to be sent
headers Optional. Specifies additional headers, like From, Cc, and
Bcc. When sending an email, it must contain a From header.
This can be set with this parameter or in the php.ini file.
34
parameters Optional. Specifies an additional parameter to the sendmail
program
SETTINGS TO SEND MAIL THROUGH GMAIL SMTP
Go to C:\xampp\php and open the php.ini file.
Find [mail function] by pressing ctrl + f.
Search and pass the following values:
SMTP=smtp.gmail.com
smtp_port=587
Sunil P. Emekar
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t“
go to C:\xampp\sendmail and open the sendmail.ini file.
Find [sendmail] by pressing ctrl + f.
Search and pass the following values
smtp_server=smtp.gmail.com
smtp_port=587 or 25 //use any of them
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=Your-Gmail-Password
35
[email protected](optional)
SCRIPT TO SEND MAIL:
<?php
$to_email = "[email protected]";
$subject = "Simple Email Test via PHP";
Sunil P. Emekar
$body = "Hi, This is test email send by PHP Script";
$headers = "From: [email protected]";
37