Sei sulla pagina 1di 122

Chapter one

SERVER SIDE SCRIPTING BASIC


◦ Introduction to server- ◦ Write Comments
side scripting ◦ Utilize Variables
◦ Server-side scripting ◦ Manipulate Strings
languages ◦ Manipulate Numbers
◦ Use Basic Syntax ◦ Work with constants
◦ Send Data to the Web
Browser

1
Introduction to HTTP
o HTTP is a communication standard governing the requests and
responses that take place between the browser running on the
end user’s computer and the web server.
o The server’s job is to accept a request from the client and
attempt to reply to it in a meaningful way, usually by serving up a
requested web page that’s why the term server is used.
oThe natural counterpart to a server is a client, so that term is
applied both to the web browser and the computer on which it’s
running.

2
Introduction contd…
o Between the client and the server there can be several other devices,
such as routers, proxies, gateways, and so on.
oThey serve different roles in ensuring that the requests
and responses are correctly transferred between the client and server.
o Typically, they use the Internet to send this information.
o A web server can usually handle multiple simultaneous connections
and when not communicating with a client spends its time listening
for an incoming connection.
oWhen one arrives, the server sends back a response to confirm its
receipt.

3
The Request/Response
Procedure
o At its most basic level,
the request/response
process consists of a web
browser asking the web
server to send it a web
page and the server
sending back the page.
o The browser then takes
care of displaying the
page.

4
Each step in the request and response
sequence is as follows:
1.You enter http://server.com into your browser’s address
bar.
2.Your browser looks up the IP address for server.com.
3.Your browser issues a request for the home page at server.com.
4. The request crosses the Internet and arrives at the server.com
web server.
5. The web server, having received the request, looks for the web
page on its hard disk.
6. The web page is retrieved by the server and returned to the
browser.
7.Your browser displays the web page.

5
For dynamic web pages, the procedure is a little more
involved, because it may bring both PHP and MySQL into
the mix.

6
The steps for a dynamic client/server
request/response sequence:
1.You enter http://server.com into your browser’s address bar.
2.Your browser looks up the IP address for server.com.
3.Your browser issues a request to that address for the web
server’s home page.
4. The request crosses the Internet and arrives at the server.com
web server.
5. The web server, having received the request, fetches the
home page from its hard disk.

7
Contd…
6. With the home page now in memory, the web server notices that it is
a file incorporating PHP scripting and passes the page to the PHP
interpreter.
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains MySQL statements, which the PHP
interpreter now passes to the MySQL database engine.
9. The MySQL database returns the results of the statements back to the
PHP interpreter.
10. The PHP interpreter returns the results of the executed PHP code,
along with the results from the MySQL database, to the web server.
11. The web server returns the page to the requesting client, which
displays it.

8
Introduction to server-side scripting
o The server is where the Web page and other content lives.
oThe server sends pages to the user/client on request.
The process is:
o The user requests a Web page from the server the script in the
page is interpreted by the server creating or changing the page
content to suit the user and the occasion and/or passing data.
o Around the page in its final form is sent to the user and then
cannot be changed using server-side scripting

9
Server side scripting…
o Server-side scripting tends to be used for allowing users to
have individual accounts and providing data from databases. It
allows a level of privacy, personalization and provision of
information that is very powerful.
o E-commerce and social networking sites all rely heavily on
server- side scripting.
o Server-side scripts are never seen by the user.
o They run on the server and generate results which are sent to
the user.

10
Introduction to PHP

11
PHP Introduction

What is PHP?
 PHP is a recursive acronym for “PHP: Hypertext
Pre-processor”.
 It is a widely-used open source general-purpose
scripting language that is especially suited for web
development and can be embedded into HTML.

12
PHP Introduction
PHP is a server-side scripting language
PHP scripts are executed on the server
PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
PHP is open source software
 PHP is free to download and use

13
PHP Introduction
PHP runs on different platforms (Windows, Linux,
Unix, etc.)
PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
PHP is FREE to download from the official PHP
resource: www.php.net
PHP is easy to learn and runs efficiently on the server
side

14
PHP Introduction

 Instead of lots of commands to output HTML, PHP


pages contain HTML with embedded code that does
"something" (like in the next slide, it outputs "Hi, I'm a
PHP script!").
 The PHP code is enclosed in special start and end
processing instructions
 <?php and ?> that allow you to jump into and out of
"PHP mode."

15
PHP Introduction

16
PHP Introduction

 PHP code is executed on the server,


generating HTML which is then sent to the
client.
 The client would receive the results of
running that script, but would not know
what the underlying code was.

17
PHP Getting Started

On windows, you can download and install WAMP.


With one installation and you get an Apache webserver,
database server and php.
http://www.wampserver.com
Xampp: http://www.apachefriends.org
On mac, you can download and install MAMP.
http://www.mamp.info/en/index.html

18
PHP Hello World

Above is the PHP source code.

19
PHP Hello World
It renders as HTML that looks like this:

20
PHP Hello World
This program is extremely simple and you
really did not need to use PHP to create a
page like this.
 All it does is display: Hello World using
the PHP echo() statement.
Think of this as a normal HTML file which
happens to have a set of special tags
available to you that do a lot of interesting
things.
21
PHP Comments

 In PHP, we use // or # to make a single-line


comment
 /* ….. */ to make a large comment block.

22
PHP Variables
Variables are used for storing values, like text strings,
numbers, Booleans or arrays.
When a variable is declared, it can be used over and
over again in your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP:

23
PHP Variables

 In PHP, a variable does not need to be declared before adding a


value to it.
In the example above, you see that you do not have to tell PHP
which data type the variable is.
 PHP automatically converts the variable to the correct data type,
depending on its value.

24
PHP Variables
A variable name must start with a letter or an
underscore "_" -- not a number.
 A variable name can only contain alpha-
numeric characters, underscores (a-z, A-Z, 0-9,
and _ )
A variable name should not contain spaces.
 If a variable name is more than one word, it
should be separated with an underscore
($my_string) or with capitalization ($myString).

25
Send Data to the Web
Browser
The only way that your embedded PHP code will display anything
in a user’s browser program is either by means of statements that
print something to output or by calling functions that, in turn,
call print statements.
Echo and print
The two most basic constructs for printing to output are echo and
print. Their language status is somewhat confusing, because they
are basic constructs of the PHP language, rather than being
functions.
o As a result, they can be used either with parentheses or without
them.
26
echo
echo is not actually a function (it is a language construct), so
you are not required to use parentheses with it.
echo does not behave like a function, so it cannot always be used
in the context of a function.
Additionally, if you want to pass more than one parameter
to echo, the parameters must not be enclosed within
parentheses.
The simplest use of echo is to print a string as argument, for
example:
 echo “This will print in the user’s browser window.”;

27
echo contd…
Or equivalently:
echo(“This will print in the user’s browser window.”);
 Both of these statements will cause the given sentence to be
displayed, without displaying the quote signs.
 You can also give multiple arguments to the unparenthesized
version of echo, separated by commas, as in:
echo “This will print in the “, “user’s browser window.”;
 The parenthesized version, however, will not accept
multiple arguments:
echo (“This will produce a “, “PARSE ERROR!”);

28
Print
 int print ( string $arg )
 Outputs arg.
 print is not actually a real function (it is a language construct) so you are not
required to use parentheses with its argument list.
 The only difference to echo is that print only accepts a single
argument.
 Unlike echo, print returns a value, which represents whether or
not the print statement succeeded.
 The value returned by print is always 1.
 Both echo and print are usually used with string arguments, but PHP’s type
flexibility means that you can throw pretty much any type of argument at
them without causing an error.

29
Print cont..
 For example, the following two lines will print exactly the same
thing:
 print(“3.14159”); // print a string
 print(3.14159); // print a number
 Technically, what is happening in the second line is that, because
print expects a string argument, the floating-point version of the
number is converted to a string value before print gets hold of it.
However, the effect is that both print and echo will reliably print
out numbers as well as string arguments.

30
PHP Data Types
 PHP data types are used to hold different types of data or
values.
 PHP supports 8 primitive data types that can be categorized
further in 3 types:
 Scalar Types
Compound Types
Special Types

31
Scalar Types
There are 4 scalar data types in PHP.
1. boolean
2. integer
3. Float(double)
4. string

32
Compound Types
There are 2 compound data types in PHP.
1. array
2. object

33
Special Types
There are 2 special data types in PHP.
1. Resource:is a special variable, holding a reference to an external
resource.
2. NULL :The special NULL value represents a variable with no value.
NULL is the only possible value of type null.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
There is only one value of type null, and that is the case-insensitive
constant NULL.
34
Constants
 In addition to variables, which may be reassigned, PHP offers constants,
which have a single value throughout their lifetime.
 Constants do not have a $ before their names, and by convention the
names of constants usually are in uppercase letters.
Option-1: by using built-in function define()
he name of a constant follows the same rules as any label in PHP. A valid
constant name starts with a letter or underscore, followed by any number
of letters, numbers, or underscores.
A constant is case-sensitive by default. By convention, constant identifiers
are always uppercase.

35
Constants contd..
 Likesuperglobals, the scope of a constant is global.You can access
constants anywhere in your script without regard to scope.
<?php
//Valid constant names
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");
// Invalid constant names
define("2FOO", "something");
echo FOO;
?>

36
Chapter 2

HTML Forms and Server


Side Scripting

37
PHP Concatenation
variable names in php must be different from keywords or reserved
words.
Variable names are case-sensitive. For example $Abc and $abc are two
different variables.
The concatenation operator (.) is used to put two string values
together.
To concatenate two string variables together, use the concatenation
operator:

38
PHP Concatenation
The output of the code on the last slide will be:

 If we look at the code you see that we used the concatenation operator
two times.
 This is because we had to insert a third string (a space character), to
separate the two strings.

39
PHP Operators
 Operators are used to operate on values.
There are four classifications of operators:

1. Arithmetic
2. Assignment
3. Comparison
4. Logical

40
PHP Operators

41
PHP Operators

42
PHP Operators

43
PHP Operators

44
Conditional operator or ternary
Operator
Which expression is used to generate the value returned depends on
the result of a test expression:
(expression)?returned_if_expression_is_true:returned_if_expression_i
s_false;
If the test expression evaluates to true, the result of the second
expression is returned; otherwise, the value of the third expression is
returned.
<?php
$age=10;
Echo ($age>18)? ” you are welcome!”:”strictly forbidden!”;
?>

45
Precedence of PHP
Operators
Operator precedence determines the grouping of
terms in an expression.
This affects how an expression is evaluated.
Certain operators have higher precedence than
others; for example, the multiplication operator has
higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13,
not 20 because operator * has higher precedence
than + so it first get multiplied with 3*2 and then
adds into 7.

46
Here operators with the highest precedence appear at
the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence
operators will be evaluated first.

47
Flow-Control Statements
PHP supports a number of traditional
programming constructs for controlling the flow of
execution of a program.
Conditional statements, such as if/else and switch,
allow a program to execute different pieces of code,
or none at all, depending on some condition.
Loops, such as while and for, support the repeated
execution of particular code.

48
PHP Conditional Statements
Very often when you write code, you want to
perform different actions for different decisions.
You can use conditional statements in your code
to do this.
In PHP we have the following conditional
statements...

49
PHP Conditional Statements
 if statement - use this statement to execute some code only if a
specified condition is true.
 if...else statement - use this statement to execute some code if a
condition is true and another code if the condition is false.
 if...elseif....else statement - use this statement to select one of
several blocks of code to be executed.
The ?, or ternary, operator is similar to the if statement but
returns a value derived from one of two expressions separated by
a colon.
 switch statement - use this statement to select one of many blocks of code
to be executed.

50
PHP Conditional Statements
The following example will output "Have a nice weekend!" if the current
day is Friday:

51
PHP Conditional Statements
Use the if....else statement to execute some code if a condition is true
and another code if a condition is false.

52
PHP Conditional Statements

If more than one line should be


executed if a condition is
true/false, the lines should be
enclosed within curly braces { }

53
PHP Conditional Statements

The following example will output


"Have a nice weekend!" if the
current day is Friday, and "Have a
nice Sunday!" if the current day is
Sunday. Otherwise it will output
"Have a nice day!":

54
PHP Conditional Statements
 Use the switch statement to select one of many blocks of code to be executed.

55
PHP Conditional Statements
For switches, first we have a single expression n
(most often a variable), that is evaluated once.
The value of the expression is then compared with
the values for each case in the structure. If there is a
match, the block of code associated with that case is
executed.
Use break to prevent the code from running into
the next case automatically. The default statement is
used if no match is found.

56
PHP Conditional Statements

57
PHP Loops
 Oftenwhen you write code, you want the same
block of code to run over and over again in a row.
 Instead of adding several almost equal lines in
a script we can use loops to perform a task like
this.
In PHP, we have the following looping
statements:

58
PHP Loops
while - loops through a block of code while a
specified condition is true
 do...while - loops through a block of code once,
and then repeats the loop as long as a specified
condition is true
 for - loops through a block of code a specified
number of times
foreach - loops through a block of code for each
element in an array.

59
PHP Loops - While
The while loop executes a block of code while a condition is true. The
example below defines a loop that starts with
i=1. The loop will
continue to run as
long as i is less
than, or equal to 5.
i will increase by 1
each time the loop
runs:

60
PHP Loops - While

61
PHP Loops – Do ... While
The do...while statement will always execute the
block of code once, it will then check the condition,
and repeat the loop while the condition is true.
The next example defines a loop that starts with
i=1. It will then increment i with 1, and write some
output.
Then the condition is checked, and the loop will
continue to run as long as i is less than, or equal to
5:
62
PHP Loops – Do ... While

63
PHP Loops – Do ... While

64
PHP Loops - For

65
PHP Loops - For
Parameters:
 init: Mostly used to set a counter (but can be any
code to be executed once at the beginning of the
loop)
condition: Evaluated for each loop iteration. If it
evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
 increment: Mostly used to increment a counter
(but can be any code to be executed at the end of the
loop)
66
PHP Loops - For
The example below defines a loop that starts
with i=1. The loop will continue to run as long as
i is less than, or equal to 5. i will increase by 1
each time the loop runs:

67
PHP Loops - For

68
PHP Arrays
An array variable is a storage area holding a number or
text.
The problem is, a variable will hold only one value.
An array is a special variable, which can store multiple
values in one single variable.

69
PHP Arrays
If you have a list of items (a list of car names, for
example), storing the cars in single variables could
look like this:
 $studentone=“Abebe”;
$studenttwo=“Kebede”;
$studentthree=“Almaz”;

70
PHP Arrays
However, what if you want to loop through the cars
and find a specific one? And what if you had not 3
cars, but 300?
 The best solution here is to use an array.
An array can hold all your variable values under a
single name.
And you can access the values by referring to the
array name.
 Each element in the array has its own index so that
it can be easily accessed.

71
PHP Arrays
In PHP, there are three kind of arrays:
 Numeric array - An array with a numeric index
 Associative array - An array where each ID key
is associated with a value
Multidimensional array - An array containing
one or more arrays

72
PHP Numeric Arrays

A numeric array stores each array element with


a numeric index.
There are two methods to create a numeric
array.

73
PHP Numeric Arrays
In the following example the index is automatically
assigned (the index starts at 0):
$student=array(“kebede”, ”Bekele”,”Almaz”);
In the following example we assign the index manually:
$student[0]=“Kebede”;
$student[1]=“Bekele”;
$student[0]=“Almaz”;

74
PHP Numeric Arrays

In the following example you access the variable


values by referring to the array name and index:
<?php
echo $student[0];
?>

75
PHP Loops - Foreach

For every loop iteration, the value of the current


array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop
iteration, you'll be looking at the next array value.
76
PHP Loops - Foreach
The following example demonstrates a loop that will print the values of
the given array:

77
PHP Loops - Foreach

78
PHP Associative Arrays
With an associative array, each ID key is
associated with a value.
When storing data about specific named values,
a numerical array is not always the best way to
do it.
 With associative arrays we can use the values
as keys and assign values to them.

79
PHP Associative Arrays

associatearray.txt

80
PHP Multidimensional Arrays

 In a multidimensional array, each element in


the main array can also be an array.
 And each element in the sub-array can be an
array, and so on.

81
Using Autoglobals
PHP includes various predefined global arrays, called
autoglobals or superglobals
Autoglobals contain client, server, and environment
information that you can use in your scripts
Autoglobals are associative arrays – arrays whose
elements are referred to with an alphanumeric key instead
of an index number

82
Using Autoglobals
(continued)
PHP autoglobals

83
Using Autoglobals
(continued)
$_GET is the default method for submitting a form.
$_GET appends form data as one long string to the URL
specified by the action attribute
google.com/search?hl=en&source=hp&q=php
$_GET and $_POST allow you to access the values of
forms that are submitted to a PHP script

84
Using Autoglobals
(continued)
$_POST sends form data as a transmission separate from the
URL specified by the form action attribute
<form action=“submitpage.php"
method=“post">
<input type="text" name=“variable1">
<input type="text" name=“variable2">
<input type="text" name=“name">
<input type="submit">
</form>

85
Autoglobals
$_SERVER[“PHP_SELF”];
$_SERVER[“SERVER_SOFTWARE”];
$_SERVER[“SERVER_PROTOCOL”];
$_GET[“name”];
$_GET[“address”];

86
PHP Functions

To keep the script from being executed when the page loads, you can
put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.

87
 The simplest form of a function is defined with the keyword function followed by a
function name and a set of parentheses and a set of curly brackets for the function
definition.
 function DeleteRows() {}
Function names are case insensitive. A function that is declared as MyFunc() can be
called as myfunc(); or MYFUNC().
 To make this function do something we need to write the logic between the curly
brackets.
 The code in a function follows the exact same structure as any PHP script.
 Any function that is callable outside of the function is also
available inside the function. This is true for both built-in functions and user-defined
functions.

88
 Functions can be called as a statement or as the right side of a calculation,
assuming the function has a return value.
 A function can return a value using the return statement in conjunction with a
value or object.
 The return statement can return a value, an object, or even nothing at all.
 return stops the execution of the function and sends the value back to the
calling code.

89
Variable Scope
 Variables defined outside of a function are not directly accessible inside the
function.
 This is called scope. In PHP there is the global scope that includes all variables
defined outside of any function.
 These can be accessed directly by any code that is executed outside of any
function.
 Variables defined inside a function are only available to code defined as part of
the function.
 There are two ways to access variables from the global scope from within a
function.

90
 The first way is to use the super global variable $GLOBALS.
The $GLOBALS variable is an array of all the variables defined
in the global scope.
 The second option is to use the keyword global in front of one
or more variable names separated by commas. This will create
and reference the variable in the global scope.

91
PHP Functions
A function will be executed by a call to the function.

 Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)

92
Example
<?php
Function message()
{
return “welcome to php programming”;
}
echo ‘this example shows how to define and call function’;
echo “message()”;
?>

93
PHP Functions - Parameters
Adding parameters...
To add more functionality to a function, we can
add parameters.
A parameter is just like a variable.
Parameters are specified after the function
name, inside the parentheses.

94
Regular Expressions
Defined: A method of specifying a search string using a number
of special characters that can precisely match a substring.
Purpose: Regular expressions allow you to perform complex pattern
matching on strings. A small regular expression can replace the need for a
large amount of code
Example for e-mail validation:
^[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\.[A-Za-z]{2,4}

99
Regex: Delimiters
The regex definition is always bracketed by delimiters, usually a ‘/’:
$regex = ’/php/’;
Matches: ‘php’, ’I love php’
Doesn’t match: ‘PHP’
‘I love ph’

100
Regex: First impressions
Note how the regular expression matches anywhere in the
string: the whole regular expression has to be matched, but the
whole data string doesn’t have to be used.
It is a case-sensitive comparison.

101
Regex: Case insensitive
Extra switches can be added after the last delimiter. The only switch we will use
is the ‘i’ switch to make comparison case insensitive:
$regex = ’/php/i’;
Matches: ‘php’, ’I love pHp’,
‘PHP’
Doesn’t match: ‘I love ph’

102
Regex: Character groups
A regex is matched character-by-character.You can specify multiple options for a
character using square brackets:
$regex = ’/p[hu]p/’;
Matches: ‘php’, ’pup’
Doesn’t match: ‘phup’, ‘pop’,
‘PHP’

103
Regex: Character groups
You can also specify a digit or alphabetical range in square brackets:
$regex = ’/p[a-z1-3]p/’;
Matches: ‘php’, ’pup’,
‘pap’, ‘pop’, ‘p3p’
Doesn’t match: ‘PHP’, ‘p5p’

104
Regex: Predefined Classes
There are a number of pre-defined classes available:

\d Matches a single character that is a digit


(0-9)

\s Matches any whitespace character


(includes tabs and line breaks)

\w Matches any “word” character:


alphanumeric characters plus underscore.
Regex: Predefined classes
$regex = ’/p\dp/’;
Matches: ‘p3p’, ’p7p’,
Doesn’t match: ‘p10p’, ‘P7p’

$regex = ’/p\wp/’;
Matches: ‘p3p’, ’pHp’, ’pop’
Doesn’t match: ‘phhp’

106
Regex: the Dot
The special dot character matches anything apart
from line breaks:
$regex = ’/p.p/’;
Matches: ‘php’, ’p&p’,
‘p(p’, ‘p3p’, ‘p$p’
Doesn’t match: ‘PHP’, ‘phhp’

107
Regex: Repetition
There are a number of special characters that indicate the
character group may be repeated:

? Zero or 1 times
* Zero or more times
+ 1 or more times
{a,b} Between a and b times
Regex: Repetition
$regex = ’/ph?p/’;
Matches: ‘pp’, ’php’,
Doesn’t match: ‘phhp’, ‘pap’

$regex = ’/ph*p/’;
Matches: ‘pp’, ’php’, ’phhhhp’
Doesn’t match: ‘pop’, ’phhohp’

109
Regex: Repetition
$regex = ’/ph+p/’;
Matches: ‘php’, ’phhhhp’,
Doesn’t match: ‘pp’, ‘phyhp’

$regex = ’/ph{1,3}p/’;
Matches: ‘php’, ’phhhp’
Doesn’t match: ‘pp’, ’phhhhp’

110
Regex: Bracketed repetition
The repetition operators can be used on bracketed
expressions to repeat multiple characters:
$regex = ’/(php)+/’;
Matches: ‘php’, ’phpphp’,
‘phpphpphp’
Doesn’t match: ‘ph’, ‘popph’

111
Regex: Anchors
So far, we have matched anywhere within a string (either the
entire data string or part of it). We can change this behaviour
by using anchors:

^ Start of the string


$ End of string
Regex: Anchors
With NO anchors:
$regex = ’/php/’;
Matches: ‘php’, ’php is great’,
‘in php we..’
Doesn’t match: ‘pop’

113
Regex: Anchors
With start and end anchors:
$regex = ’/^php$/’;
Matches: ‘php’,
Doesn’t match: ’php is great’,
‘in php we..’, ‘pop’

114
Regex: Escape special
characters
We have seen that characters such as ?,.,$,*,+
have a special meaning.
If we want to actually use them as a literal, we
need to escape them with a backslash.
$regex = ’/p\.p/’;
Matches: ‘p.p’
Doesn’t match: ‘php’, ‘p1p’

115
So.. An example
Lets define a regex that matches an email:

$emailRegex = '/^[a-z\d\._-]+@([a-z\d-]+\.)+[a-
z]{2,6}$/i‘;

Matches: ‘rob@example.com’,
‘rob@subdomain.example.com’
‘a_n_other@example.co.uk’
Doesn’t match: ‘rob@exam@ple.com’
‘not.an.email.com’

116
Boolean Matching
We can use the function preg_match() to test whether a string matches or not.

// match an email
$input = ‘rob@example.com’;
if (preg_match($emailRegex,$input) {
echo ‘Is a valid email’;
} else {
echo ‘NOT a valid email’;
}

117
Pattern replacement
We can use the function preg_replace() to replace any matching strings.

// strip any multiple spaces


$input = ‘Some comment string’;
$regex = ‘/\s\s+/’;
$clean = preg_replace($regex,’ ‘,$input);
// ‘Some comment string’

118
Validating User Input and
Some Sanitization
 Validating user input is the first (and one of the most important steps) to
securing your site.
 Validating means verifying the data coming into your script is type of data you
want, is in the correct format, and is the right length.
Without checking these, your site is vulnerable.
Depending on what your script does, it can lead to your site going down,
displaying bad information, giving the bad guys access to getting information
from users, and much more.

119
Know the incoming data
 The first step in validating your data is knowing what data should come in.
 Now that we have an idea of what information will be coming to our script, we
need to verify that we have the correct data, type of data, a limit on the length of
data, and that we aren’t using anything beyond the data we need.

120
Determining if Form Variables
Contain Values
The isset() function determines whether a variable has
been declared and initialized (or “set”)
The empty() function determines whether a variable is
empty.
Pass to both functions the name of the variable you want to
check.
Use the is_numeric() function to test whether a
variable contains a numeric string

121
PHP filter_input() Function
The filter_input() function gets an external variable (e.g. from form input) and
optionally filters it.
This function is used to validate variables from insecure sources, such as user
input.

122
Syntax
filter_input(type, variable, filter, options)

Parameter Description
type •Required. The input type to check for. Can be one of the
following:INPUT_GET
•INPUT_POST
•INPUT_COOKIE
•INPUT_SERVER
•INPUT_ENV

variable Required. The variable name to check

filter Optional. Specifies the ID or name of the filter to use. Default is


FILTER_DEFAULT, which results in no filtering

options Optional. Specifies one or more flags/options to use. Check each filter for
possible options and flags

123
Example
<?php
if (!filter_input(INPUT_GET,"email",FILTER_VALIDATE_EMAIL)) {
echo("Email is not valid");
} else {
echo("Email is valid");
}
?>

124
Testing if Form Variables
Contain Numeric Values
if (isset($_GET['height']) && isset($_GET['weight'])) {
if (is_numeric($_GET['weight']) && is_numeric($_GET['height'])) {
$BodyMass = $_GET['weight'] / ($_GET['height']
* $_GET['height']) * 703;
printf("<p>Your body mass index is %d.</p>",
$BodyMass);
}
else
echo "<p>You must enter numeric values!</p>";
}
125
THE END OF
CHAPTER TWO!

126

Potrebbero piacerti anche