0% found this document useful (0 votes)
6 views

Unit 4 - Creating and Validating Forms

The document outlines the creation and validation of forms in web-based applications using PHP, emphasizing the importance of form controls and validation techniques. It explains HTTP basics, the differences between GET and POST methods, and how to manage cookies and sessions. Additionally, it covers various form elements, validation rules, and the use of PHP superglobal arrays to handle user input effectively.

Uploaded by

iqbalshaikh64684
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 4 - Creating and Validating Forms

The document outlines the creation and validation of forms in web-based applications using PHP, emphasizing the importance of form controls and validation techniques. It explains HTTP basics, the differences between GET and POST methods, and how to manage cookies and sessions. Additionally, it covers various form elements, validation rules, and the use of PHP superglobal arrays to handle user input effectively.

Uploaded by

iqbalshaikh64684
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

WEB BASED APPLICATION

DEVELOPMENT WITH PHP


WBP [22619]

UNIT – IV
CREATING AND VALIDATING
FORMS

Sunil Prakashrao Emekar


Lecturer in Computer Engg.
Government Polytechnic Karad

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

 form is a section of an HTML document that contains


elements such as radio buttons, text boxes, check
boxes, and option lists.
 HTML form elements are also known as controls.

 The program that processes the form is called a


Common Gateway Interface (CGI) program. – In our
case its PHP
 Many applications require that some information
contained on a form be verified using a validation
process.
 Two common ways to validate information on a form
are by using CGI programs and JavaScripts.
 HTML Form:
<FORM name="Contact" action="welcome.html"
method="post">
</form>

 Input Element:
Sunil P. Emekar
5
HTTP BASICS

 The Web runs on HTTP, or HyperText Transfer


Protocol.
 This protocol governs how web browsers request files

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.

 Both GET and POST create an array (e.g. array( key1


=> value1, key2 => value2, key3 => value3, ...)). This
array holds key/value pairs, where keys are the names
of the form controls and values are the input data
from the user.
7
 When to use GET?
 Information sent from a form with the GET method
is visible to everyone (all variable names and values are
displayed in the URL).
 GET also has limits on the amount of information to send.
The limitation is about 2000 characters.
 However, because the variables are displayed 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

 Developers prefer POST for sending form data.


VARIABLES
 PHP creates six global arrays that contain the EGPCS
(environment, GET, POST, cookies, and server) information.
 $_COOKIE
 Contains any cookie values passed as part of the request, where
the keys of the Array are the names of the cookies

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

 The HTML <form> element can contain one or


more of the following form elements:

 <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="text"> (default value)

 <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:

<button type="button" > Button Text </button>

Or create button using <input >


<input type="button" value="Click Here"/>
TEXT & TEXTAREA
 Text:
Example:
<input type="text" id="fname" name="fname"
value="Enter Name here" maxlength="100">

 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

<input type="checkbox" name="vehicle2"


id="vehicle2"><label for="vehicle2"> I Have
Car</label>

Checked attribute for default checked.


RADIO BUTTON

 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:

 <label for="cars">Choose a car:</label>


<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="Tata">Tata</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
SERVER INFORMATION
 The $_SERVER array contains a lot of useful
information from the web server.

Sunil P. Emekar
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script

$_SERVER['GATEWAY_INTE Returns the version of the Common Gateway Interface


RFACE'] (CGI) the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server

$_SERVER['SERVER_NAME'] Returns the name of the host server

$_SERVER['SERVER_SOFTW Returns the server identification string (such as


ARE'] Apache/2.2.24)
$_SERVER['SERVER_PROTO Returns the name and revision of the information 18
COL'] protocol (such as HTTP/1.1)
$_SERVER['REQUEST_METHOD' Returns the request method used to access the page (such as
] POST)

$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as


1377687496)

$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query
string

$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request

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_HOST'] Returns the Host header from the current request

$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable
because not all user-agents support it)

$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol

$_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

1. A Web page having many forms


 We can have many <form> tag inside a web page
<form>….</form> targeting different PHP scripts.

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

 Validation means check the input submitted by the


user.
 There are two types of validation are available in

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);

if ( $length < 10 && $length > 10) {


$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else { 25
echo "Your Mobile number is: " .$mobileno;
}
COOKIE
 PHP cookie is a small piece of information which is
stored at client browser. It is used to recognize the
user.
 Cookie is created at server side and saved to client

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.

 Expiry − This specify a future time in seconds since 00:00:00 GMT


on 1st Jan 1970. After this time cookie will become inaccessible. If
this parameter is not set then cookie will automatically expire
when the Web Browser is closed.
 Path − This specifies the directories for which the cookie is valid.

 Domain − This can be used to specify the domain name

 Security − This can be set to 1 to specify that the cookie should


only be sent by secure transmission using HTTPS otherwise set to 27
0 which mean cookie can be sent by regular HTTP.
ACCESSING COOKIES WITH PHP

 PHP $_COOKIE superglobal variable is used to get


cookie.

Sunil P. Emekar
 Example
 $value=$_COOKIE["CookieName"];//returns cookie value

 We also use the isset() function to find out if the


cookie is set:

28
DELETING COOKIE WITH PHP

 To delete a cookie, use the setcookie() function


with an expiration date in the past:

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

 all session variable values are stored in the


global $_SESSION variable:

Sunil P. Emekar
 Example:

echo $_SESSION["user"];

32
DESTROYING A PHP SESSION

 A PHP session can be destroyed by


session_destroy() function.
 This function does not need any argument and a

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:

<?php unset($_SESSION[“session_var”]); ?>


<?php session_destroy(); ?>

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]";

if (mail($to_email, $subject, $body, $headers)) {


echo "Email successfully sent to $to_email...";
} else {
echo "Email sending failed...";
}
?> 36
Sunil P. Emekar
 Make sure Less secure app access for your gmail
account is on

37

You might also like