SlideShare a Scribd company logo
Unit - III
 A key part of most PHP applications is the ability to
accept input from the person using the application.
 One of the most common ways to receive input from the
user of a Web application is via an HTML form.
How forms work
Web Server
User
User requests a particular URL
XHTML Page supplied with Form
User fills in form and submits.
Another URL is requested and the
Form data is sent to this page either in
URL or as a separate piece of data.
XHTML Response
How HTML Forms Work
 An HTML form, or Web form, is simply a collection of
HTML elements embedded within a standard Web page.
 By adding different types of elements, you can create
different form fields, such as text fields, pull - down
menus, checkboxes, and so on.
 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
).
 The script at the specified URL should be capable of accepting
and processing the form data; more on this in a moment.
 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,
 post can send much larger amounts of form data.
Form fields: password input
 Use a starred text input for passwords.
<label for=“pw">Password</label>
<input type=“password"
name=“passwd"
id=“pw"
size="20"/>
Form fields: text input
 If you need more than 1 line to enter data, use a textarea.
<label for="desc">Description</label>
<textarea name=“description”
id=“desc“
rows=“10” cols=“30”>
Default text goes here…
</textarea>
Form fields: text area
 name=“…” is the name of the field.You will use this
name in PHP to access the data.
 id=“…” is label reference string – this should be the
same as that referenced in the <label> tag.
 rows=“…” cols=“..” is the size of the displayed
text box.
Form fields: drop down
<label for="tn">Where do you live?</label>
<select name="town" id="tn">
<option value="swindon">Swindon</option>
<option value="london”
selected="selected">London</option>
<option value=“bristol">Bristol</option>
</select>
Form fields: drop down
 name=“…” is the name of the field.
 id=“…” is label reference string.
 <option value=“…” is the actual data sent back to
PHP if the option is selected.
 <option>…</option> is the value displayed to the
user.
 selected=“selected” this option is selected by
default.
Form fields: radio buttons
<input type="radio"
name="age"
id="u30“
checked=“checked”
value="Under30" />
<label for="u30">Under 30</label>
<br />
<input type="radio"
name="age"
id="thirty40"
value="30to40" />
<label for="thirty40">30 to 40</label>
Form fields: radio buttons
 name=“…” is the name of the field.All radio boxes with
the same name are grouped with only one selectable at a
time.
 id=“…” is label reference string.
 value=“…” is the actual data sent back to PHP if the
option is selected.
 checked=“checked” this option is selected by
default.
Form fields: check boxes
What colours do you like?<br />
<input type="checkbox"
name="colour[]"
id="r"
checked="checked"
value="red" />
<label for="r">Red</label>
<br />
<input type="checkbox"
name="colour[]"
id="b"
value="blue" />
<label for="b">Blue</label>
Hidden Fields
<input type="hidden"
name="hidden_value"
value="My Hidden Value" />
 name=“…” is the name of the field.
 value=“…” is the actual data sent back to PHP.
Submit button..
 A submit button for the form can be created with the
code:
<input type="submit"
name="submit"
value="Submit" />
Capturing Form Data with PHP
 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.
Superglobal Array
 $_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
GET vs. POST
 Both GET and POST create an array (e.g. array( key => value,
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.
 Both GET and POST are treated as $_GET and $_POST.
These are superglobals, which means that they are always
accessible, regardless of scope - and you can access them from
any function, class or file without having to do anything special.
 $_GET is an array of variables passed to the current script via
the URL parameters.
 $_POST is an array of variables passed to the current script
via the HTTP POST method.
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,
it is possible to bookmark the page.
 This can be useful in some cases.
 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) and 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.
 However, because the variables are not displayed in the
URL, it is not possible to bookmark the page.
 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.
 Example:
< input type=”text ” name=”emailAddress” value=”” / >
 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”];
 Exercise:
 Create a membership form with firstname, lastname,
username, password, course selection (radio buttons),
submit and reset buttons.
 Take the input from user and display the data in tabular
form on the next page.
Handling Empty Form Fields
 When nothing is sent at all for a field, PHP doesn’t create an
element for the field in the $_POST , $_GET , or $_REQUEST
array.
 So if you attempt to access the element, it will generate a PHP
notice.
 A good idea to write a code so that it doesn‘t generate notices.
 This helps to ensure the robustness and security of an
application.
 This means that you should check for the presence of a
submitted form field before using it, rather than assuming that it
exists
 Use PHP functions such as isset() or array_key_exists()
for that
 Example:
<?php if ( isset( $_POST[“name"] ) )
echo $_POST[“name"]?>
Dealing with Multi - Value Fields
 The following form fields are capable of sending multiple values
to the server:
<select name=”favoriteWidgets” size=”3” multiple=”multiple”>
<option value=”superWidget”>The SuperWidget</option>
<option value=”megaWidget”>The MegaWidget</option>
<option value=”wonderWidget”>TheWonderWidget</option>
</select>
 how to handle multi - value fields in your PHP scripts?
 One way 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.
< select name=”favoriteWidgets[]” id=”favoriteWidgets” size=”3”
multiple=”multiple” ... < /select >
 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
Example:
<form action=test.php method=get>
<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>
<input type=submit value=submit>
</form>
<?php
$widgetlist = "";
if ( isset( $_GET['favoriteWidgets'] ) ) {
foreach ( $_GET['favoriteWidgets'] as $widget ) {
$widgetlist = $widgetlist . $widget;
}
}
echo rtrim ($widgetlist, ',');
?>
What is the $_SERVER["PHP_SELF"]
variable?
 The $_SERVER["PHP_SELF"] is a super global variable
that returns the filename of the currently executing
script.
 <form method='post' action='$_SERVER[‘PHP_SELF’]’>
 So, the $_SERVER["PHP_SELF"] sends the submitted
form data to the page itself, instead of jumping to a
different page.
 This way, the user will get error messages on the same
page as the form.
PHP Form Security
 The $_SERVER["PHP_SELF"] variable can be used by
hackers!
 If PHP_SELF is used in your page then a user can enter a
slash (/) and then some Cross Site Scripting (XSS)
commands to execute.
 $_SERVER["PHP_SELF"] exploits can be avoided by using
the htmlspecialchars() function.
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
HTTP Header() Function
 The header() function sends a raw HTTP header to a client.
 This is some extra information, such as type of programme making the request, date
requested, should it be displayed as a HTML document, how long the document is,
and a lot more besides.
 One of the things HTTP HEADER also does is to give status information.This could
be whether the page was found (404 errors), and the location of the document. If
you want to redirect your users to another page, here's an example:
<?PHP
header("Location: http://www.test.com/");
?>
<html>
<body>
</body>
</html>
 Note how the header code goes before any HTML. If you put header code after the
HTML, you'll get an error along the lines of "Cannot modify header information."
PHP include and require Statements
 The include and require statements are used to insert
useful codes written in other files, in the flow of
execution.
 Include and require are identical, except upon
failure:
 require will produce a fatal error (E_COMPILE_ERROR) and
stop the script
 include will only produce a warning (E_WARNING) and the
script will continue
 include.php.
 Now take a look at the code for this page:
<HTML>
<HEAD>
<TITLE>Include files</TITLE>
</HEAD>
<BODY>
<H3>Normal text here </H3>
Normal text written in a HTML Editor
<H3>Include File here</H3>
<?PHP include "textfile.txt" ; ?>
// <?PHP require "textfile.txt" ; ?>
</ BODY>
</ HTML >
 The require_once statement is identical to require
except PHP will check if the file has already been
included, and if so, not include (require) it again.
 The include_once statement is identical to include except
PHP will check if the file has already been included, and if
so, not include (require) it again.
PHP Error Handling
 When creating scripts and web applications, error
handling is an important part.
 If your code lacks error checking code, your program may
look very unprofessional and you may be open to security
risks.
Basic Error Handling: Using the die()
function
 The die() function prints a message and exits the current
script.
 Syntax
 die(message)
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
Basic Error Handling: Using the exit()
function
 The exit() function prints a message and exits the current
script.
 Syntax
 exit(message)
<?php
if(!file_exists("welcome.txt"))
{
exit("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
Trigger an Error
 In a script where users can input data it is useful to
trigger errors when an illegal input occurs.
 In PHP, this is done by the trigger_error() function.
 Example
<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>
Notice: Value must be 1 or below
in C:webfoldertest.php on line 6
Creating a Custom Error Handler
 A special function that can be called when an error
occurs in PHP.
 This function must be able to handle a minimum of
two parameters (error level and error message)
 But can accept up to five parameters (optionally: file, line-
number, and the error context)
 Syntax
 error_function (error_level,error_message,
error_file,error_line,error_context)
Unit - III.pptxbgffhjxfjdfjfgjnsnsnshdhsjsksjsjsjsjsjsjsjsjsldksk
 Example
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
 The code above is a simple error handling function.
 When it is triggered, it gets the error level and an error
message.
 It then outputs the error level and message and
terminates the script.
Set Error Handler
 Once you define your custom error handler you need to
set it using PHP built-in library
set_error_handler function.
 The set_error_handler() function sets a user-defined
function to handle errors.
 This function is used to create your own way of handling
errors during runtime.
 It is possible to change the error handler to apply for
only some errors, that way the script can handle different
errors in different ways.
 set_error_handler("customError");
 <?php
//error handler function
function customError($errno, $errstr, $errfile, $errline)
{
echo "<b>Error:</b> [$errno] $errstr";
echo " Error on line $errline in $errfile<br />";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?> Error: [8] Undefined variable: test
Error on line 15 in C:xampphtdocstest1.php
Preserving State With Query Strings,
Cookies, and Sessions
 HTTP is stateless Protocol.
 Any data you have stored is forgotten about when the
page has been sent to the client and the connection is
closed
 Query strings to store small amounts of data in the URL
 Cookies to store larger amounts of data in the browser itself
 Sessions to store even larger amounts of data, and store it in a
much more secure fashion
Saving State with Query Strings
 Query strings are a quick, convenient way to pass small
amounts of data between browser requests.
 Common uses of query strings include remembering a
user ’ s entered keywords when using a search function,
identifying which topic within a forum to display to the
user, and specifying which post within a blog to display.
 Query string data is very easy for the user to alter,
because it’s visible and editable within the browser’s
address bar.
 Therefore, query strings should be used only in situations
where sending incorrect data won’t compromise security.
Passing a query string to a page
 Exemple 1:
 <a href="page.php?name=Joe”> Name </a>
 Example 2:
 <a href="page.php? name=Joe&age=24"> Name and Age</a>
 If the user then clicks this link, page.php is run, and the
query string data ( firstName=John & age=34 ) is passed
to the page.php script.
 Data has been transmitted from one script execution to
the next.
Accessing Data in Query Strings
 To access the field names and values in a query string on
page.php, $_GET superglobal array is used
<? php
$Name = $_GET[“name”];
$age = $_GET[“age”];
?>
Maintaining State in PHP
Cookies & Sessions
 Why to use Session and Cookie?
 HTTP is stateless Protocol.
 Any data you have stored is forgotten about when the page has
been sent to the client and the connection is closed.
 Cookie is tiny bits of information that a web site could store
on the client's machine that were sent back to the web site
each time a new page was requested.
 Each cookie could only be read by the web site that had
written it.
What is a Cookie?
 A cookie is a small text file that is stored on a user’s
computer.
 Each cookie on the user’s computer is connected to a
particular domain.
 Each cookie be used to store up to 4kB of data.
 A maximum of 20 cookies can be stored on a user’s PC
per domain.
 A cookie is often used to identify a user.
 Cookies are usually set in an HTTP header
 cookies are not encrypted by default, so unless you
encrypt your data yourself, you should not store any
sensitive information in them.
There are three steps involved in
identifying returning users:
1. User sends a request for page at www.example.com for
the first time.
page request
2. Server sends back the page xhtml to the browser AND
stores some data in a cookie on the user’s PC.
cookie data
xhtml
3. When next time browser sends any request to web
server then it sends those cookies information to the
server and server uses that information to identify the
user.
page request
cookie data
Setting Cookies with PHP:
setcookie(name [,value [,expire [,path [,domain
[,secure]]]]])
name = cookie name
value = data to store (string)
expire = UNIX timestamp when the cookie expires.
Default is that cookie expires when browser is closed.
path = Path on the server within and below which the
cookie is available on.
domain = Domain at which the cookie is available for.
secure = If cookie should be sent over HTTPS
connection only. Default false.
Set a cookie - examples
<?php
setcookie(‘name’,’Alex’);
?>
This command will set the cookie called name on the
user’s PC containing the data Alex.
It will be available to all pages in the same directory or
subdirectory of the page that set it (the default path and
domain).
It will expire and be deleted when the browser is closed
(default expire).
How to Retrieve a Cookie Value?
 The PHP $_COOKIE variable is used to retrieve a cookie
value.
In the example below, we retrieve the value of the cookie
named "user" and display it on a page:
 <?php
// Print a cookie
echo $_COOKIE[“name"];
// A way to view all cookies
print_r($_COOKIE);
?>
 In the following example we use the isset() function to
find out if a cookie has been set:
 <html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
echo "Welcome guest!<br>";
?>
</body>
</html>
How to Delete a Cookie?
 When deleting a cookie you should assure that the
expiration date is in the past.
 Delete example:
 <?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
Session
 An alternative way to make data accessible across the
various pages of an entire website is to use a PHP
Session.
 A session creates a file in a temporary directory on the
server where registered session variables and their values
are stored.
 This data will be available to all pages on the site during
that visit.
 A session ends when the user loses the browser or after
leaving the site, the server will terminate the session after
a predetermined period of time, commonly 30 minutes
duration.
When should you use sessions?

Need for data to stored on the server

Unique session information for each user

Transient data, only relevant for short time

Data does not contain secret information

Similar to Cookies, but it is stored on the server

More secure, once established, no data is sent back and
forth between the machines

Works even if cookies are disabled

Example: we want to count the number of “hits” on our
web page.
Starting a PHP Session
 Before you can store user information in your PHP
session, you must first start up the session
<?php session_start(); ?>
<html>
<body>
</body>
</html>
Storing a session variable
 Use the $_SESSION associative array to store and
retrieve session data.
Session Example 1
 <?php
 session_start();
 if (!isset($_SESSION["intVar"]) ){
 $_SESSION["intVar"] = 1;
 } else {
 $_SESSION["intVar"]++;
 }
 echo "<p>In this session you have accessed this
page " . $_SESSION["intVar"] . "times.</p>";
 ?>
Ending sessions
unset($_SESSION[‘name’])
– Remove a session variable
session_destroy()
– Destroys all data registered to a session
– does not unset session global variables and cookies
associated with the session
– Not normally done - leave to timeout

More Related Content

PPT
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
 
PDF
web2_lec6.pdf
ssuser893014
 
PPTX
5. Formshcfsjhfajkjsfjsjfjksafjsfjkjfhjsafjsajkgfjskafkjas.pptx
berihun18
 
PPTX
Working with data.pptx
SherinRappai
 
PPTX
forms.pptx
asmabagersh
 
PDF
Web app development_php_07
Hassen Poreya
 
PDF
Form handling in php
Fahad Khan
 
PDF
PHP-Part4
Ahmed Saihood
 
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
 
web2_lec6.pdf
ssuser893014
 
5. Formshcfsjhfajkjsfjsjfjksafjsfjkjfhjsafjsajkgfjskafkjas.pptx
berihun18
 
Working with data.pptx
SherinRappai
 
forms.pptx
asmabagersh
 
Web app development_php_07
Hassen Poreya
 
Form handling in php
Fahad Khan
 
PHP-Part4
Ahmed Saihood
 

Similar to Unit - III.pptxbgffhjxfjdfjfgjnsnsnshdhsjsksjsjsjsjsjsjsjsjsldksk (20)

PPTX
Web Application Development using PHP Chapter 5
Mohd Harris Ahmad Jaal
 
PPT
Lecture7 form processing by okello erick
okelloerick
 
PPTX
Form Handling using PHP
Nisa Soomro
 
PPTX
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
PDF
03 the htm_lforms
IIUM
 
PPTX
Web Techniques like Cookies and Sessions
SonaliAbhang
 
PPTX
2-Chapter Edit.pptx debret tabour university
alemunuruhak9
 
PPTX
WorkingwithFormsinPHPpptx__2024_10_17_19_07_07 2.pptx
harleensingh985
 
DOCX
Php forms and validations by naveen kumar veligeti
Naveen Kumar Veligeti
 
PDF
WIT UNIT-4.pdf
jashmithakakavakam
 
PPT
Web forms and html lecture Number 4
Mudasir Syed
 
PDF
Making web forms using php
krishnapriya Tadepalli
 
PDF
Introduction to php web programming - get and post
baabtra.com - No. 1 supplier of quality freshers
 
PDF
GET and POST in PHP
Vineet Kumar Saini
 
ODP
Form Processing In Php
Harit Kothari
 
PPT
Chapter 07 php forms handling
Dhani Ahmad
 
PPT
PHP-04-Forms.ppt
NatureLifearabhi
 
ODP
PHP BASIC PRESENTATION
krutitrivedi
 
PPT
PHP-04-Forms PHP-04-Forms PHP-04-Forms PHP-04-Forms
ZahraWaheed9
 
PPTX
HNDIT1022 Week 03 Part 2 Theory information.pptx
IsuriUmayangana
 
Web Application Development using PHP Chapter 5
Mohd Harris Ahmad Jaal
 
Lecture7 form processing by okello erick
okelloerick
 
Form Handling using PHP
Nisa Soomro
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
03 the htm_lforms
IIUM
 
Web Techniques like Cookies and Sessions
SonaliAbhang
 
2-Chapter Edit.pptx debret tabour university
alemunuruhak9
 
WorkingwithFormsinPHPpptx__2024_10_17_19_07_07 2.pptx
harleensingh985
 
Php forms and validations by naveen kumar veligeti
Naveen Kumar Veligeti
 
WIT UNIT-4.pdf
jashmithakakavakam
 
Web forms and html lecture Number 4
Mudasir Syed
 
Making web forms using php
krishnapriya Tadepalli
 
Introduction to php web programming - get and post
baabtra.com - No. 1 supplier of quality freshers
 
GET and POST in PHP
Vineet Kumar Saini
 
Form Processing In Php
Harit Kothari
 
Chapter 07 php forms handling
Dhani Ahmad
 
PHP-04-Forms.ppt
NatureLifearabhi
 
PHP BASIC PRESENTATION
krutitrivedi
 
PHP-04-Forms PHP-04-Forms PHP-04-Forms PHP-04-Forms
ZahraWaheed9
 
HNDIT1022 Week 03 Part 2 Theory information.pptx
IsuriUmayangana
 
Ad

Recently uploaded (20)

PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PDF
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PDF
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
Landforms and landscapes data surprise preview
jpinnuck
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Understanding operators in c language.pptx
auteharshil95
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Ad

Unit - III.pptxbgffhjxfjdfjfgjnsnsnshdhsjsksjsjsjsjsjsjsjsjsldksk

  • 2.  A key part of most PHP applications is the ability to accept input from the person using the application.  One of the most common ways to receive input from the user of a Web application is via an HTML form.
  • 3. How forms work Web Server User User requests a particular URL XHTML Page supplied with Form User fills in form and submits. Another URL is requested and the Form data is sent to this page either in URL or as a separate piece of data. XHTML Response
  • 4. How HTML Forms Work  An HTML form, or Web form, is simply a collection of HTML elements embedded within a standard Web page.  By adding different types of elements, you can create different form fields, such as text fields, pull - down menus, checkboxes, and so on.  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 >
  • 5.  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 ).  The script at the specified URL should be capable of accepting and processing the form data; more on this in a moment.
  • 6.  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,  post can send much larger amounts of form data.
  • 7. Form fields: password input  Use a starred text input for passwords. <label for=“pw">Password</label> <input type=“password" name=“passwd" id=“pw" size="20"/>
  • 8. Form fields: text input  If you need more than 1 line to enter data, use a textarea. <label for="desc">Description</label> <textarea name=“description” id=“desc“ rows=“10” cols=“30”> Default text goes here… </textarea>
  • 9. Form fields: text area  name=“…” is the name of the field.You will use this name in PHP to access the data.  id=“…” is label reference string – this should be the same as that referenced in the <label> tag.  rows=“…” cols=“..” is the size of the displayed text box.
  • 10. Form fields: drop down <label for="tn">Where do you live?</label> <select name="town" id="tn"> <option value="swindon">Swindon</option> <option value="london” selected="selected">London</option> <option value=“bristol">Bristol</option> </select>
  • 11. Form fields: drop down  name=“…” is the name of the field.  id=“…” is label reference string.  <option value=“…” is the actual data sent back to PHP if the option is selected.  <option>…</option> is the value displayed to the user.  selected=“selected” this option is selected by default.
  • 12. Form fields: radio buttons <input type="radio" name="age" id="u30“ checked=“checked” value="Under30" /> <label for="u30">Under 30</label> <br /> <input type="radio" name="age" id="thirty40" value="30to40" /> <label for="thirty40">30 to 40</label>
  • 13. Form fields: radio buttons  name=“…” is the name of the field.All radio boxes with the same name are grouped with only one selectable at a time.  id=“…” is label reference string.  value=“…” is the actual data sent back to PHP if the option is selected.  checked=“checked” this option is selected by default.
  • 14. Form fields: check boxes What colours do you like?<br /> <input type="checkbox" name="colour[]" id="r" checked="checked" value="red" /> <label for="r">Red</label> <br /> <input type="checkbox" name="colour[]" id="b" value="blue" /> <label for="b">Blue</label>
  • 15. Hidden Fields <input type="hidden" name="hidden_value" value="My Hidden Value" />  name=“…” is the name of the field.  value=“…” is the actual data sent back to PHP.
  • 16. Submit button..  A submit button for the form can be created with the code: <input type="submit" name="submit" value="Submit" />
  • 17. Capturing Form Data with PHP  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.
  • 18. Superglobal Array  $_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
  • 19. GET vs. POST  Both GET and POST create an array (e.g. array( key => value, 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.  Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.  $_GET is an array of variables passed to the current script via the URL parameters.  $_POST is an array of variables passed to the current script via the HTTP POST method.
  • 20. 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, it is possible to bookmark the page.  This can be useful in some cases.  GET may be used for sending non-sensitive data.
  • 21. 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) and 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.  However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
  • 22.  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.  Example: < input type=”text ” name=”emailAddress” value=”” / >  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”];
  • 23.  Exercise:  Create a membership form with firstname, lastname, username, password, course selection (radio buttons), submit and reset buttons.  Take the input from user and display the data in tabular form on the next page.
  • 24. Handling Empty Form Fields  When nothing is sent at all for a field, PHP doesn’t create an element for the field in the $_POST , $_GET , or $_REQUEST array.  So if you attempt to access the element, it will generate a PHP notice.  A good idea to write a code so that it doesn‘t generate notices.  This helps to ensure the robustness and security of an application.  This means that you should check for the presence of a submitted form field before using it, rather than assuming that it exists
  • 25.  Use PHP functions such as isset() or array_key_exists() for that  Example: <?php if ( isset( $_POST[“name"] ) ) echo $_POST[“name"]?>
  • 26. Dealing with Multi - Value Fields  The following form fields are capable of sending multiple values to the server: <select name=”favoriteWidgets” size=”3” multiple=”multiple”> <option value=”superWidget”>The SuperWidget</option> <option value=”megaWidget”>The MegaWidget</option> <option value=”wonderWidget”>TheWonderWidget</option> </select>
  • 27.  how to handle multi - value fields in your PHP scripts?  One way 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.
  • 28. < select name=”favoriteWidgets[]” id=”favoriteWidgets” size=”3” multiple=”multiple” ... < /select >  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
  • 29. Example: <form action=test.php method=get> <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> <input type=submit value=submit> </form>
  • 30. <?php $widgetlist = ""; if ( isset( $_GET['favoriteWidgets'] ) ) { foreach ( $_GET['favoriteWidgets'] as $widget ) { $widgetlist = $widgetlist . $widget; } } echo rtrim ($widgetlist, ','); ?>
  • 31. What is the $_SERVER["PHP_SELF"] variable?  The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.  <form method='post' action='$_SERVER[‘PHP_SELF’]’>  So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page.  This way, the user will get error messages on the same page as the form.
  • 32. PHP Form Security  The $_SERVER["PHP_SELF"] variable can be used by hackers!  If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.  $_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function. <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  • 33. HTTP Header() Function  The header() function sends a raw HTTP header to a client.  This is some extra information, such as type of programme making the request, date requested, should it be displayed as a HTML document, how long the document is, and a lot more besides.  One of the things HTTP HEADER also does is to give status information.This could be whether the page was found (404 errors), and the location of the document. If you want to redirect your users to another page, here's an example: <?PHP header("Location: http://www.test.com/"); ?> <html> <body> </body> </html>  Note how the header code goes before any HTML. If you put header code after the HTML, you'll get an error along the lines of "Cannot modify header information."
  • 34. PHP include and require Statements  The include and require statements are used to insert useful codes written in other files, in the flow of execution.  Include and require are identical, except upon failure:  require will produce a fatal error (E_COMPILE_ERROR) and stop the script  include will only produce a warning (E_WARNING) and the script will continue
  • 35.  include.php.  Now take a look at the code for this page: <HTML> <HEAD> <TITLE>Include files</TITLE> </HEAD> <BODY> <H3>Normal text here </H3> Normal text written in a HTML Editor <H3>Include File here</H3> <?PHP include "textfile.txt" ; ?> // <?PHP require "textfile.txt" ; ?> </ BODY> </ HTML >
  • 36.  The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.  The include_once statement is identical to include except PHP will check if the file has already been included, and if so, not include (require) it again.
  • 37. PHP Error Handling  When creating scripts and web applications, error handling is an important part.  If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
  • 38. Basic Error Handling: Using the die() function  The die() function prints a message and exits the current script.  Syntax  die(message) <?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>
  • 39. Basic Error Handling: Using the exit() function  The exit() function prints a message and exits the current script.  Syntax  exit(message) <?php if(!file_exists("welcome.txt")) { exit("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>
  • 40. Trigger an Error  In a script where users can input data it is useful to trigger errors when an illegal input occurs.  In PHP, this is done by the trigger_error() function.  Example <?php $test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?> Notice: Value must be 1 or below in C:webfoldertest.php on line 6
  • 41. Creating a Custom Error Handler  A special function that can be called when an error occurs in PHP.  This function must be able to handle a minimum of two parameters (error level and error message)  But can accept up to five parameters (optionally: file, line- number, and the error context)  Syntax  error_function (error_level,error_message, error_file,error_line,error_context)
  • 43.  Example function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Ending Script"; die(); }  The code above is a simple error handling function.  When it is triggered, it gets the error level and an error message.  It then outputs the error level and message and terminates the script.
  • 44. Set Error Handler  Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function.  The set_error_handler() function sets a user-defined function to handle errors.  This function is used to create your own way of handling errors during runtime.  It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways.  set_error_handler("customError");
  • 45.  <?php //error handler function function customError($errno, $errstr, $errfile, $errline) { echo "<b>Error:</b> [$errno] $errstr"; echo " Error on line $errline in $errfile<br />"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?> Error: [8] Undefined variable: test Error on line 15 in C:xampphtdocstest1.php
  • 46. Preserving State With Query Strings, Cookies, and Sessions
  • 47.  HTTP is stateless Protocol.  Any data you have stored is forgotten about when the page has been sent to the client and the connection is closed  Query strings to store small amounts of data in the URL  Cookies to store larger amounts of data in the browser itself  Sessions to store even larger amounts of data, and store it in a much more secure fashion
  • 48. Saving State with Query Strings  Query strings are a quick, convenient way to pass small amounts of data between browser requests.  Common uses of query strings include remembering a user ’ s entered keywords when using a search function, identifying which topic within a forum to display to the user, and specifying which post within a blog to display.
  • 49.  Query string data is very easy for the user to alter, because it’s visible and editable within the browser’s address bar.  Therefore, query strings should be used only in situations where sending incorrect data won’t compromise security.
  • 50. Passing a query string to a page  Exemple 1:  <a href="page.php?name=Joe”> Name </a>  Example 2:  <a href="page.php? name=Joe&age=24"> Name and Age</a>  If the user then clicks this link, page.php is run, and the query string data ( firstName=John & age=34 ) is passed to the page.php script.  Data has been transmitted from one script execution to the next.
  • 51. Accessing Data in Query Strings  To access the field names and values in a query string on page.php, $_GET superglobal array is used <? php $Name = $_GET[“name”]; $age = $_GET[“age”]; ?>
  • 52. Maintaining State in PHP Cookies & Sessions  Why to use Session and Cookie?  HTTP is stateless Protocol.  Any data you have stored is forgotten about when the page has been sent to the client and the connection is closed.  Cookie is tiny bits of information that a web site could store on the client's machine that were sent back to the web site each time a new page was requested.  Each cookie could only be read by the web site that had written it.
  • 53. What is a Cookie?  A cookie is a small text file that is stored on a user’s computer.  Each cookie on the user’s computer is connected to a particular domain.  Each cookie be used to store up to 4kB of data.  A maximum of 20 cookies can be stored on a user’s PC per domain.  A cookie is often used to identify a user.  Cookies are usually set in an HTTP header  cookies are not encrypted by default, so unless you encrypt your data yourself, you should not store any sensitive information in them.
  • 54. There are three steps involved in identifying returning users: 1. User sends a request for page at www.example.com for the first time. page request
  • 55. 2. Server sends back the page xhtml to the browser AND stores some data in a cookie on the user’s PC. cookie data xhtml
  • 56. 3. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. page request cookie data
  • 57. Setting Cookies with PHP: setcookie(name [,value [,expire [,path [,domain [,secure]]]]]) name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed. path = Path on the server within and below which the cookie is available on. domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS connection only. Default false.
  • 58. Set a cookie - examples <?php setcookie(‘name’,’Alex’); ?> This command will set the cookie called name on the user’s PC containing the data Alex. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).
  • 59. How to Retrieve a Cookie Value?  The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page:  <?php // Print a cookie echo $_COOKIE[“name"]; // A way to view all cookies print_r($_COOKIE); ?>
  • 60.  In the following example we use the isset() function to find out if a cookie has been set:  <html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br>"; else echo "Welcome guest!<br>"; ?> </body> </html>
  • 61. How to Delete a Cookie?  When deleting a cookie you should assure that the expiration date is in the past.  Delete example:  <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
  • 62. Session  An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.  A session creates a file in a temporary directory on the server where registered session variables and their values are stored.  This data will be available to all pages on the site during that visit.  A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.
  • 63. When should you use sessions?  Need for data to stored on the server  Unique session information for each user  Transient data, only relevant for short time  Data does not contain secret information  Similar to Cookies, but it is stored on the server  More secure, once established, no data is sent back and forth between the machines  Works even if cookies are disabled  Example: we want to count the number of “hits” on our web page.
  • 64. Starting a PHP Session  Before you can store user information in your PHP session, you must first start up the session <?php session_start(); ?> <html> <body> </body> </html>
  • 65. Storing a session variable  Use the $_SESSION associative array to store and retrieve session data.
  • 66. Session Example 1  <?php  session_start();  if (!isset($_SESSION["intVar"]) ){  $_SESSION["intVar"] = 1;  } else {  $_SESSION["intVar"]++;  }  echo "<p>In this session you have accessed this page " . $_SESSION["intVar"] . "times.</p>";  ?>
  • 67. Ending sessions unset($_SESSION[‘name’]) – Remove a session variable session_destroy() – Destroys all data registered to a session – does not unset session global variables and cookies associated with the session – Not normally done - leave to timeout