WP Chapter Five
WP Chapter Five
CLIENT
Server
SIDE
Browser
HTML
JavaScript
CSS
Script
Database Engine
3
Server-Side
Browser Server
Apache
SERVER SIDE
4
Client side vs Server side scripting
Client-side Server-side
Scripts are stored on the client (engine Scripts are stored on the server
is in browser) (engine is on server)
Scripts can be modified by the end Scripts cannot be modified by the end
user user
Browser-dependent Browser-independent
Source code can be viewed Source code can’t be viewed
Can’t communicate with a database Can communicate with a database
2. <?
// Some code
?>
3. <script language=“PHP">
// Some code here
</script>
• When a PHP file is requested, the PHP interpreter parses the entire
file
• Any content within PHP delimiter tags is interpreted, and
the output substituted
• Any other content (i.e. not within PHP delimiter tags) is
simply passed on unchanged
• This allows us to easily mix PHP and other content (ex:
HTML)
• All PHP statements end with a semi-colon (;)
• The semicolon is a separator which is used to distinguish one set
of instructions from another.
• With PHP, there are two basic statements to output text in the
browser: echo and print.
Example 1
HTML 5 Document
<!DOCTYPE html>
<html> Root HTML Tag
<head>
<title>Simple PHP Example</title>
Document Head
</head>
<body>
<?php echo "<p><h1>Output</h1>";
D print"<h2>Output</h2>";
O Print"<h3>Output</h3></p>";
C PHP Code
?>
<script language="PHP">
B echo "<b>More PHP Output</b>";
O echo "New line in source but not rendered";
D
echo "<br/>";
Y
echo "New line rendered but not in source";
</script>
</body>
</html>
Example2
<html>
<head>
<title> Hello world </title>
</head>
<body>
<?php
print 'Hello, World!';
echo "<br/>";
echo "Hello, World!";
echo phpversion();
?>
</body></html>
The use of include() function
<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php");
Script execution
• There are two methods for executing PHP scripts:
via the Web server, and
The command-line interface (CLI).
• The first method will be used almost exclusively in this course,
so you may ignore the CLI for now.
1. Upload your .php file to your Web account (i.e., within the
www-home directory on wapserver or httdocs directory on
xampserver).
2. Make sure the permissions are set correctly;
3. Navigate to the file with a Web browser.
17
Cont...
• The PHP processor has two modes: copy (HTML) and
interpret (PHP).
• PHP processor takes a PHP document as input and
produces an HTML document file
• When it finds HTML code in the input file, simply
copies it to the output file
• When it finds PHP script, it interprets it and send any
output of the script to the output file
• This new output file is sent to the requesting browser.
• The client never sees the PHP script.
18
Basic PHP Facts
• PHP variables are case sensitive, but reserved
words and function names are not.
E.g
• while, WHILE, While, and wHiLe are same
19
Comments in PHP
• A comment in PHP code is a line that is not executed as a part of the
program.
• Its only purpose is to be read by someone who is looking at the
code.
• In PHP, three different kinds
(a) // ... ; for single line
(b) # ... ; for single line
(c) /* ... */ ; for multiple-line
<html>
<body>
<?php
//This is a comment
# this is also a comment
/*
This is a comment
block
*/
?></body>
PHP Variables
• Variables are containers used to temporarily store values.
• These values can be numbers, text, or much more complex
data.
• All variables in PHP start with a $ sign symbol.
<?php
$txt="Hello World!";
$x=16;
?>
• In PHP, a variable does not need to be declared before adding a
value to it.
Rules for PHP variable
• A variable starts with the $ sign, followed by the name of the
variable
• A variable name must begin with a letter or the underscore
character.
• A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
• A variable name should not contain spaces
• Variable names are case sensitive ($y and $Y are two different
variables)
Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Php variable example!";
$x = 30;
$y = 20.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
PHP Variable Scopes
• PHP has three different variable scopes:
local
global
static
Local scope
29
Fundamental variable types
• Numeric
integer. Integers (±2 raised 31); values outside this range
are converted to floating-point.
float. Floating-point numbers.
• Boolean: true or false; PHP internally resolves these to 1 (one)
and 0 (zero) respectively.
• string: String of characters.
• array: An array stores multiple values in one single variable.
• object :an object is a data type which stores data and
information on how to process that data. In PHP, an object
must be explicitly declared.
e.g. $myCar = new Car("black", "Volvo");
30
Cont…
• Resource:
• A handle to something that is not PHP data (e.g., image data, database query
result).
• Or in other words, Resource is to represent a PHP extension resource (e.g.
Database query, open file, database connection, etc).
• Null :
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• Variables can also be emptied by setting the value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?> 31
Cont....
• PHP has a useful function named var_dump() that prints the
current type and value for one or more variables.
• Arrays and objects are printed recursively with their values
indented to show structure.
<?php
$a = 35; Output of the code
int(35)
$b = "Programming is fun!";
string(19) "Programming is
$c = array(1, 1, 2, 3.5); fun!"
array(4) {
var_dump($a,$b,$c); [0]=> int(1)
?> [1]=>int(1)
[2]=>int(2)
[3]=>float(3.5)) }
}}}]]]]]]]]]][[[[[
32
PHP Strings
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or
double quotes.
'I am a string in single quotes’
"I am a string in double quotes"
• All strings must start and finish with the same type of quote -
single or double.
• Only one type of quote mark is important when defining any
string, single (') or double (").
$string_1 = "This is a string in double quotes";
$string_0 = ‘’ // a string with zero characters
33
String Concatenation Operator
• To concatenate two string variables together, use the dot (.)
operator:
E.g
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 ." " .$txt2;
?>
Output
Hello World! What a nice day!
PHP String Functions
The strlen()function
Reverse a String
• The PHP strrev() function reverses a string:
E.g <?php
echo strrev("Hello world!"); //output=!dlrow olleH
?>
The str_replace() function
• The PHP str_replace() function replaces some
characters with some other characters in a string.
<?php
echo str_replace("world", “PHP", "Hello world!");
?> Output: Hello PHP!
• The example below replaces the text "world" with
“PHP":
PHP Constants
• A constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
• A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
Note: Unlike variables, constants are automatically global across the entire script.
• Syntax
define(name, value, case-insensitive)
// name: Specifies the name of the constant // value: Specifies the value of the constant
//case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
• E. g
<?php
define("GREETING", "Welcome to Mekdela Amba University!");
echo GREETING;
?>
or
<?php
define("GREETING", "Welcome to Mekdela Amba University!", true);
echo greeting;
Example PHP String functions
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 ." " .$txt2; // String concatenation function
echo "<br/>";
echo strlen($txt1); // string length function
echo "<br/>";
echo strpos("Hello world!","world"); // String position function
echo "<br/>";
echo str_word_count($txt1); // string words count function
echo "<br/>";
echo strrev($txt1); // string reverse function
echo "<br/>";
echo str_replace("world", "PHP", "Hello world!");// string replace
function
PHP Operators
• Operators are used to perform operations on variables
and values.
• PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
PHP Arithmetic Operators
Operator Name Example Result
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
PHP Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same
type
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the
same type
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP Increment / Decrement Operators
<?php statements;
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
PHP Looping - For Loops
E.g
<?php for(initialization; condition; increment)
{
echo "The number is: $x <br>";
}
?>
Foreach loop
• For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
E.g. <?php
$age = array("Peter"=>"35", "Ben"=>"37",
<?php
"Joe"=>"43");
$x=array("one","two","three");
foreach($x as $value) foreach($age as $x => $val) {
{ echo "$x = $val<br>";
echo $value . "<br />"; }
?>
}
PHP Functions
• A function is a block of statements that can be used repeatedly in a
program.
• A function will be executed by a call to the function.
• When called (or invoked), the function’s code is executed and
performs a particular task.
• A user-defined function declaration starts with the word function.
Syntax:
• Note: variables names are case sensitive in PHP, function names are
not!)
• A function name must start with a letter or an underscore.
Example
<html>
<head><title>Writing PHP Function</title></head><body>
<?php
function writeMessage(){ // Defining a PHP Function
echo "You are really a nice person, Have a nice time!<br/>";
}
writeMessage(); /* Calling a PHP Function */
function addFunction($num1, $num2)
//Writing PHP Function with Parameters
{
$sum = $num1 + $num2;
return $sum;
}
$result= addFunction(10, 20); // Calling a PHP Function with parameter
echo "Sum of the two numbers is : $result<br/>";
?></body></html>
PHP Functions - Return values
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
PHP Arrays
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Loop Through an Associative Array
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x. ", Value=" . $x_value;
echo "<br>";
}
?>
PHP - Sort Functions For Arrays
79
PHP GET and POST Methods
81
Example - $_POST
82
$_GET
• The $_GET variable is an array of variable names and values
sent by the HTTP GET method
• The $_GET variable is used to collect values from a form
with method="get“
• This method should not be used when sending passwords
or other sensitive information!
• Information sent from a form with the GET method is visible
to everyone (it will be displayed in the browser's address
bar) and it has limits on the amount of information to send
(max. 2000 characters)
83
Example - $_GET
<html> <html>
<body> <head>
<title>get method</title>
<form action="welcome.php" </head>
method="get">
Name: <input type="text" <body>
name="name"> Welcome <?php echo
$_GET["name"];?>.<br/>
Age: <input type="text" name="age">
<input type="submit"> You are <?php echo $_GET["age"];?>
years old
</form>
</body> </body>
</html> </html>
84
The $_REQUEST Variable
85
Form Validation with PHP
What is form validation?
• validation: ensuring that form's values are correct
• some types of validation:
preventing blank values (email address)
ensuring the type of values
integer, real number, currency, phone number, Social Security number,
postal address, email address, date, credit card number, ...
ensuring the format and range of values (ZIP code must be a
5-digit integer)
ensuring that values fit together (user types email twice, and
the two must match)
86
A real Form that uses validation
87
Client vs. server-side validation
• Validation can be performed:
client-side (before the form is submitted)
can lead to a better user experience, but not secure.
server-side (in PHP code, after the form is
submitted)
needed for truly secure validation, but slower
both
best mix of convenience and security, but requires most
effort to program.
88
Form validation=validation.php
<html>
<head>
<style>.error {color: #FF0000;} </style>
</head>
<body>
<?php
include ('validate.php');
?>
<h2>PHP Form Validation Example</h2>
<p>*required field.</span></p>
<form method="post" action='<?php $_SERVER["PHP_SELF"]?>' >
Name: <input type="text" name="name" value="">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
<html>
• basic idea: examine parameter values, and if they are bad, show
an error message and abort
90
Main PHP Validation Functions
/abc/
• Regexes is a sequence of characters that forms a particular
pattern.
• Provide the foundation for pattern-matching functionality
• In PHP, regexes are strings that begin and end with /
• the simplest regexes simply match a particular substring
• the above regular expression matches any string containing
"abc":
– YES: "abc", "abcdef", "defabc", ".=.abc.=.", ...
– NO: "fedcba", "ab c", "PHP", ...
94
Regular expressions
• /[a-z]/at #cat, rat, bat…
• /[a-zA-Z]/
• ~[^a-z]~ #not a-z
• (very){1, 3} #counting “very” up to 3
• /^www/ #www at the beginning
• /com$/ #com at the end
Wildcards
• A dot . matches any character except a \n line break
"/.oo.y/" matches "Doocy", "goofy", "LooNy", ...
• A trailing i at the end of a regex (after the closing / ) signifies
a case-insensitive match.
"/xen/i" matches “Xenia", “xenophobic", “Xena the warrior
princess", “XEN technologies” ...
Special characters: |, (), ^, \
• | means OR
"/abc|def|g/" matches "abc", "def", or "g"
• () are for grouping
"/(Homer|Marge) Simpson/" matches "Homer Simpson" or
"Marge Simpson"
• ^ matches the beginning of a line;
• $ the end
"/^<!--$/" matches a line that consists entirely of "<!--“
• \ starts an escape sequence
many characters must be escaped to match them literally: / \ $
.[]()^*+?
"/<br \/>/" matches lines containing <br /> tags
96
Quantifiers: *, +, ?
• * means 0 or more occurrences
"/abc*/" matches "ab", "abc", "abcc", "abccc", ...
"/a(bc)*/" matches "a", "abc", "abcbc", "abcbcbc", ...
"/a.*a/" matches "aa", "aba", "a8qa", "a!?_a", ...
• + means 1 or more occurrences
"/a(bc)+/" matches "abc", "abcbc", "abcbcbc", ...
"/Goo+gle/" matches "Google", "Gooogle", "Goooogle", ...
• ? means 0 or 1 occurrences
"/a(bc)?/" matches "a" or "abc"
97
More quantifiers: {min,max}
• {min,max} means between min and max
occurrences (inclusive)
– "/a(bc){2,4}/" matches "abcbc", "abcbcbc", or
"abcbcbcbc"
• min or max may be omitted to specify any
number
{2,} means 2 or more
{,6} means up to 6
{3} means exactly 3
98
Character sets: []
• [] group characters into a character set; will
match any single character from the set
"/[bcd]art/" matches strings containing "bart",
"cart", and "dart"
equivalent to "/(b|c|d)art/" but shorter
• inside [], many of the modifier keys act as
normal characters
"/what[!*?]*/" matches "what", "what!", "what?
**!", "what??!",
99
Character ranges: [start-end]
• inside a character set, specify a range of characters with -
"/[a-z]/" matches any lowercase letter
"/[a-zA-Z0-9]/" matches any lower- or uppercase
letter or digit
• an initial ^ inside a character set negates it
"/[^abcd]/" matches any character other than a, b, c,
or d
"/[+\-]?[0-9]+/" matches an optional + or -, followed
by at least one digit
100
Escape sequences
101
Regular expressions in PHP
• regex syntax: strings that begin and end
with /, such as "/[AEIOU]+/"
Function description
returns TRUE if string matches
preg_match(regex, string) regex
returns a new string with all
preg_replace(regex, substrings that match regex
replacement, string) replaced by replacement
returns an array of strings from
given string broken apart using
preg_split(regex, string) the given regex as the
delimiter (similar to explode
but more powerful)
CS382 102
Regular expressions example
# replace vowels with stars
$str = "the quick brown fox";
$str = preg_replace("/[aeiou]/", "*", $str);
# "th* q**ck br*wn f*x"
# break apart into words
$words = preg_split("/[ ]+/", $str);
# ("th*", "q**ck", "br*wn", "f*x")
Or
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components = preg_split($pattern, $date);
print_r($components);
?> 103
PHP form validation w/ regexes
<?php
$state = $_REQUEST["state"];
if (!preg_match("/[A-Z]{2}/", $state)) {
<h2>Error, invalid state submitted.</h2>
}
?>
PHP
104
• Use the preg_match() function stands for
perform a regular expressions match
Example
<?php
$age=$_POST["age"];
if(!preg_match("/^[0-9]$/",$age))
echo "You entered invalid input, please try again";
else
echo "Your age is ". $age;
?>
105
<?php
$age=$_POST["age"];
if(!preg_match("/^[0-9]{1,3}$/",$age))
echo "You enterd invaid input, please try
again";
else
echo "Your age is ". $age;
?>
106
Cont..
• Using the preg_match function()
• preg_match() is a case sensitive function, which means
it treats “a” and “A” differently.
• Example
function check_field1($field_name_1)
{
if(!preg_match("/^ [a-zA-Z0-9]+$/”, $field_name_1))
return TRUE;
else The slashes “/” and “/” are delimiters, “^”
return FALSE; marks the start of string or line and the
Dollar sign “$” the end of the string, or
} line. The plus-symbol “+” means required.
107
Cont....
/^[a-zA-Z0-9 _.,:"']+$/
• We translate this regexp as:
• From the beginning to the end of the address
string check if our character is one of the
following a-z, A-Z, 0-9, space, underscore, dot,
comma, colons, double and single quotes. You
can add any character that you think may be
part of an address(+).
108