Processing PHP Forms

Anuncio
Processing PHP Forms and Server‐side Validation
05/02/2015
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
Processing PHP Forms
- Server-side Validation -
3. Code
modularization
4. Validation
examples
Grupo de Ingeniería del Software y Bases de Datos
Departamento de Lenguajes y Sistemas Informáticos
© Diseño de Amador Durán Toro, 2011
Universidad de Sevilla
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• Server-side validation and other tasks:
PHP
1. Introduction
2. Global variables:
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
PDO
1
Web client
8
2
7
4
3
Data
The variable
$_SERVER
Business Logic
The variable
$GLOBALS
•
Presentation
•
6
DBMS
5
4. Validation
examples
In today class
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
1
© Diseño de Amador Durán Toro, 2011
Web server
(with processing capability)
1
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• Predefined variables
• General:
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
– $GLOBALS ≡ Global variables
– $_SERVER ≡ Information about the running server
and configuration
– $_SESSION ≡ Session data
3. Code
modularization
4. Validation
examples
• Form processing:
– $_FILES ≡ Information of the files sent by means
of a form
Introducción a la Ingeniería del Software y a los Sistemas de Información
2
© Diseño de Amador Durán Toro, 2011
– $_REQUEST ≡ Request data, usually sent by
means of a form
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
• Definition of $GLOBALS:
– It is an associative array containing references to
all the defined global variables
– The names of such global variables act as the
array keys
3. Code
modularization
– Global variables can be used in any PHP function
or tag
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
3
© Diseño de Amador Durán Toro, 2011
4. Validation
examples
2
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
• The $_SERVER variable contains information
about the execution environment and server,
such as headers, paths, and script locations
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
4. Validation
examples
• It is an associative array, containing (among
others):
– 'PHP_SELF’: The relative path of the file (containing the script)
which is currently executing
– ‘SERVER_ADDR’: The IP address of the server under which the
current script is executing
– ‘SERVER_NAME’: The hostname of the server under which the
current script is executing
– ‘REQUEST_METHOD’: The type of request (i.e. 'GET', 'POST',…)
– ‘REMOTE_ADDR’: A string containing the IP address of the machine
that requested the current page
Introducción a la Ingeniería del Software
4
y a los Sistemas de Información
4
© Diseño de Amador Durán Toro, 2011
– ‘SERVER_PORT’: The port on the server host being used by the web
server for communication
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
• The $_REQUEST variable contains the variable values
of the HTTP request. Such values are validated on the
server-side, as we will see later
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
4. Validation
examples
• It is an associative array that contains in turn all the
elements in $_GET, $_POST, and $_COOKIE
• A way to check whether a variable has been sent in
the current request may be:
<?
if (isset ($_REQUEST[‘X’]))
echo “‘X’ is $_REQUEST[‘X’]”;
else
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
5
© Diseño de Amador Durán Toro, 2011
echo “ ‘X’ has not been sent”.
?>
3
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• To handle file uploads, we use the global $_FILES
variable
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
• It is another associative array whose keys are
the names of the file elements uploaded by
means of the form, and its associated values are
in turn arrays indexed by the following keys:
– name: the name of uploaded file as supplied by the browser
– type: the MIME type of the uploaded file (such as "image/gif“)
– size: the size of the uploaded file (in bytes)
3. Code
modularization
4. Validation
examples
– tmp_name: the location in which is stored the temporary file on the
server that holds the uploaded file
– error: an error code, that can be:
UPLOAD_ERR_OK (no
•
UPLOAD_ERR_INI_SIZE
•
UPLOAD_ERR_FORM_SIZE
error)
•
UPLOAD_ERR_PARTIAL
•
UPLOAD_ERR_NO_FILE
•
UPLOAD_ERR_NO_TMP_DIR
•
UPLOAD_ERR_CANT_WRITE
Introducción a la Ingeniería del Software y a los Sistemas de Información
6
© Diseño de Amador Durán Toro, 2011
•
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
• Example for processing $FILE:
<?
if (isset ($_FILES[‘the_name_file']) &&
($_FILES[‘the_name_file']['error'] == UPLOAD_ERR_OK)) {
$newPath = “.\\myPath\\”;
if (move_uploaded_file($_FILES[‘the_name_file']['tmp_name'], $newPath)) {
print(“File stored in $newPath“);
} else {
print (“File can not be stored in $newPath”);
3. Code
modularization
4. Validation
examples
}
} else {
print( “There was an error while uploading file:” .
$_FILES[‘the_name_file']['error'] );
?>
Introducción a la Ingeniería del Software
7
y a los Sistemas de Información
IISSI
7
© Diseño de Amador Durán Toro, 2011
}
4
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• HTTP is designed as a stateless protocol, what is a
problem for web application development
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
4. Validation
examples
• Session support in PHP consists of a way to preserve
certain data across subsequent accesses
• Modern server-side script languages (such as PHP)
have a good support for session handling on HTTP,
so that:
– Detecting whether a pair of requests belongs to the same session
• This support is provided from PHP 4.0
Introducción a la Ingeniería del Software y a los Sistemas de Información
8
© Diseño de Amador Durán Toro, 2011
– The capability for storing information associated to a session and
recovering it afterwards
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
• By default, PHP uses cookies (for storing
temporary data in the user web browser) in
order to maintain a session:
– A common problem is caused because of cookies being
disabled in the web browser (typically for security reasons)
• If cookies are disabled, PHP makes use of
hidden variables instead
4. Validation
examples
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
9
© Diseño de Amador Durán Toro, 2011
• PHP functions for session handling abstract
away such programming details
5
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
4. Validation
examples
• In PHP, each session is identified by a 32characters string (sessionID):
– So that that each user being concurrently logged
is given a different sessionID
• By default, PHP stores the session data in a
temporary file (in /tmp directory):
– A different file for each session
Introducción a la Ingeniería del Software y a los Sistemas de Información
10
© Diseño de Amador Durán Toro, 2011
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• The $_SESSION variable contains the data
concerning to a session
1. Introduction
2. Global variables:
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
4. Validation
examples
• It is an associative array, that allows to store
and retrieve the session data:
<? session_start();
session_start(); ?>
?>
<?
…
…
<?
<?
?>
?>
$_SESSION[‘user`]=$_REQUEST[‘user’];
$_SESSION[‘usuario’]=$_REQUEST[‘usuario’];
$_SESSION[‘passwd`]=$_REQUEST[‘passwd’];
$_SESSION[‘passwd’]=$_REQUEST[‘passwd’];
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
11
© Diseño de Amador Durán Toro, 2011
•
6
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
• Functions for handling PHP sessions:
– session_start: Initializes a session and allows to store
variables in $_SESSION
– session_destroy: Destroys all data saved in the session
– session_encode: Encodes the data of the current session
as a string
4. Validation
examples
– session_decode: Decodes the session data from a string
current session id
Introducción a la Ingeniería del Software y a los Sistemas de Información
12
© Diseño de Amador Durán Toro, 2011
– session_id: Gets the 32 characters containing the
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• Modularization to process the form data:
1. Introduction
$_SESSION data
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
4. Validation
examples
no
errors?
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
13
© Diseño de Amador Durán Toro, 2011
yes
7
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
<?
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
if (isset ($_SESSION[“errors”]))
$errors=$_SESSION["errors"]; Two elements in $_SESSION
to store:
?>
• Form data
…
• Errors (validation results)
<div id="div_errors">
<?
if (isset($errors)){
foreach($errors as $error){
print("<div class='error'>");
print("$error");
Errors are shown in that case
print("</div>");
In case of active session, the
}
form must recover the data
}
stored in the session, or show
?>
the default values instead
</div>
….
<div id="div_name">
<label for=“name">Name:</label>
<input id=“name" name=“name"
value= “<? echo $form[‘name‘]; ?>” />
</div>
…
3. Code
modularization
4. Validation
examples
Introducción a la Ingeniería del Software y a los Sistemas de Información
14
© Diseño de Amador Durán Toro, 2011
// The session is either initialized or recovered
session_start();
if (!isset($_SESSION[“form”]) ) {
// Default values in case of first access (no session)
$form[“name"]=“default_name”;
$form[“address"]=“default_address“;
$_SESSION[“form”] = $form;
}
else
$form=$_SESSION["form"];
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
Processing PHP Forms – Server-side Validation
• In case of no active session, it means someone or
something is trying to access this PHP by-passing the form
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
<?
1. Introduction
2. Global variables:
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
• To assign the data which
has been sent
• To validate such data
• In case of error, go back
to the form
• Otherwise, go to the page
of success
4. Validation
examples
$errors = validate($form);
if ( count ($errors) > 0 ) {
$_SESSION["errors"] = $errors;
Header("Location: form.php");
}
else Header("Location: success.php");
}
else Header("Location: form.php”);
function validate($form) {
if (empty($form[“name"]) {
$errors[] = “Name is empty";
}
• To validate the data which
has been sent from the form,
to check whether they have
been given acceptable values
...
return $errors;
}
?>
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
15
© Diseño de Amador Durán Toro, 2011
•
session_start();
if (isset($_SESSION["form"]) ){
$form[“name"]=$_REQUEST[“name"];
$form [“address"]=$_REQUEST[“address"];
$_SESSION["form"]=$form;
8
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
• Validation in PHP: Strings
<?
if (isset($_REQUEST ["name"]) && strlen($_REQUEST [“name"])>$X)
{
…
}else {
…
}
?>
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
•
More complex validations:
<?
if (isset($_REQUEST [“domain"])){
if (substrrlen($_REQUEST [“domain"],-5)=“us.es”){
…
}else {
…
}else {
…
Syntactic
}
?>
3. Code
modularization
4. Validation
examples
•
validation
Email validation:
http://code.iamcal.com/php/rfc822/rfc822.phps
•
Bank account validation:
http://en.wikipedia.org/wiki/Luhn
Introducción a la Ingeniería del Software y a los Sistemas de Información
16
© Diseño de Amador Durán Toro, 2011
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
• Validation in PHP: Numbers
• Check that is a number:
<?
if (isset($_REQUEST [“phone"]) && is_numeric($_REQUEST [“phone"])){
…
}else {
…
}
?>
• Check that is an integer:
3. Code
modularization
4. Validation
examples
$bInt = is_int( $X); // if it is an integer
$bPositive = ctype_digit($X); // If it is a positive integer
$bInt = ($X == strval(intval($X))); // if it is an integer, either positive or negative
$bDec = ($X == strval(floatval($X))); // if it is a decimal number
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
17
© Diseño de Amador Durán Toro, 2011
• Check that is a decimal number:
9
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
4. Validation
examples
• Validation in PHP: Dates
• Having a day, month and year in a separated
way:
$isValidDate = checkdate($month, $day,$year);
• Having a string for the date:
<?
$date1 = "11/15/1999“;
$date2 = "12/10/2000";
list ($month1, $day1, $year1) = explode ("/", $date1);
list ($month2, $day2, $year2) = explode ("/", $date2);
$timestamp1 = mktime (0, 0, 0, $month1, $day1, $year1);
$timestamp2 = mktime (0, 0, 0, $month2, $day2, $year2);
$diff = ($timestamp1 > $timestamp2) ?
($timestamp1 - $timestamp2) : ($timestamp2 - $timestamp1);
print(“Date difference";
print(date ("Y“, $diff) – 1970);
print(" year, " . (date ("m", $diff) - 1);
print(“ month y " . (date ("d", $diff) - 1);
print(" days.";
?>
Introducción a la Ingeniería del Software y a los Sistemas de Información
18
© Diseño de Amador Durán Toro, 2011
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
Processing PHP Forms – Server-side Validation
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
• Validation in PHP: Instants
• PHP offers the strtotime function which tries to
infer the datetime format from a string and return
the corresponding timestamp
<?
$birthdate = “2 November 1976 01:50am";
$birthdate_instant = strtotime ($birthdate);
print(“You have an age of “);
print( number_format (time() - $birthdate_instant));
print( " seconds “);
3. Code
modularization
4. Validation
examples
?>
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
19
© Diseño de Amador Durán Toro, 2011
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
10
Processing PHP Forms and Server‐side Validation
05/02/2015
Processing PHP Forms – Server-side Validation
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• Comments, suggestions, …
1. Introduction
2. Global variables:
•
The variable
$GLOBALS
•
The variable
$_SERVER
•
The variable
$_REQUEST
•
The variable
$_FILES
•
The variable
$_SESSION
3. Code
modularization
Introducción a la Ingeniería del Software y a los Sistemas de Información
IISSI
20
© Diseño de Amador Durán Toro, 2011
4. Validation
examples
11
Descargar