Professional Documents
Culture Documents
PHP
Introduction
HTML- focuses on marking up information(define the
content of web pages)
CSS- focuses on formatting and presenting
information(specify the layout of web pages)
JavaScript to program the behavior of web pages( to add
dynamic features on the client side)
PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages. ( used to add
dynamic features on the server side…including database
interaction)
Client-side Technologies
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 "\n<b>More PHP Output</b>\n";
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
<!DOCTYPE html>
<html>
<head>
<title> Hello world </title>
</head>
<body>
<?php
print 'Hello, World!';
echo "<br/>";
echo "Hello, World!";
?>
</body></html>
The use of include() fuction
<?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
• Like JS, PHP is usually purely interpreted
• Syntax and semantics are closely related to JS
• Like JS, PHP uses dynamic typing
• PHP variables are case sensitive, but reserved
words and function names are not.
E.g
• while, WHILE, While, and wHiLe are same
19
20
Comments in PHP
25
Some of the environment variables include:
• $_SERVER
Contains information about the server and the HTTP connection.
• $_COOKIE
Contains any cookie data sent back to the server from the client. Indexed by
cookie name.
• $_GET
Contains any information sent to the server as a search string as
part of the URL.
• $_POST
Contains any information sent to the server as a POST style posting
from a client form.
• $_FILE
Contains information about any uploaded files.
• $_ENV
Contains information about environmental variables on the server.
26
PHP Variable Scopes
• PHP has four different variable scopes:
local
global
static
Local scope
32
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.
(an array of values, possibly other arrays )
• 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.
33
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). You will never directly touch this type, it will be passed
to the relevant functions that know how to interact with the
specified resource.
• Null :
• data type with only one possible value: null. Marks variables
as being empty. Works with the isset() operator; will return
‘false’ for null. Example: $var=NULL;
34
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)) }
}}}]]]]]]]]]][[[[[
35
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"
• The PHP parser determines strings by finding matching quote
pairs. So, 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
36
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!
The strlen()function
<?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
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
• The “if else if” statement allows us to specify more than two alternative
statements each will be executed based on testing one or more conditions.
• Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
<?php
$d=date("D"); // A textual representation of a day (three letters)
if($d=="Fri")
echo "Have a nice weekend!";
Else if($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
PHP switch statement
•The Switch statement in PHP is used to perform one of several different
actions based on one of several different conditions.
•If you want to select one of many blocks of code to be executed, use the
Switch statement.
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
PHP Looping - For Loops
E.g
<!DOCTYPE html> for(initialization; condition; increment)
<html> statements;
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
Foreach loop
• The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
• Syntax foreach($array as $key=>$value)
foreach ($array as $value) { {
code to be executed; Code to be executed;
} }
• 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
$x=array("one","two","three");
foreach($x as $value)
{
echo $value . "<br />";
}
?>
PHP Functions
<?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"=>"4
3");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x. ", Value=" . $x_value;
echo "<br>";
}
?>
PHP - Sort Functions For Arrays
<html>
<h1><center>Calculator</center></h1>
<form action="calculator.php" method="post">
<table align="center">
<th> Choose arithmetic operator<th>Enter the values </th>
<tr>
<td>+<input type="radio" name="arithmetic" value="add" checked>
<td><input type="text" name="v1">
<tr>
<td>- <input type="radio" name="arithmetic" value="minus">
<td><input type="text" name="v2">
<tr>
<td>/ <input type="radio" name="arithmetic" value="divide">
<tr>
<td>*<input type="radio" name="arithmetic" value="multiply">
<tr>
<td><input type="submit" value="Execute" >
</table>
<h3> the Result</h3>
</form>
</html>
82
Calculator.php
<?php
$v1=$_POST['v1'];
$v2=$_POST['v2'];
$a=$_POST['arithmetic'];
require('calculator.html');
switch($a){
case 'add':
echo $v1+$v2; break;
case 'minus':
echo $v1-$v2; break;
case 'divide':
{if ($v2==0)echo"Cannot divide by zero";
else echo $v1/$v2; break;
}
case 'multiply':
echo $v1*$v2; break;
}
?> 83
Calculator.html
84
PHP GET and POST Methods
86
Example - $_POST
87
$_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)
88
Example - $_GET
<html> <html>
<head>
<body> <title>Grab form values</title>
<form action=“welcome.php" </head>
method="get">
<body>
Name: <input type="text" Welcome <?php echo
name="name"> $_GET["name"];?>.<br/>
Age: <input type="text" name="age">
You are <?php echo $_GET["age"];?>
<input type="submit"> years old
</form>
</body>
</body>
</html> </html>
89
The $_REQUEST Variable Why use $_POST?
90
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)
91
A real Form that uses validation
92
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 (why
not?)
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
93
Form validation
<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
95
Main PHP Validation Functions
98
Basic Regular Expression
/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", ...
99
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
101
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"
102
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
103
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??!",
• What regular expression matches (strings of A, C, G,
or T)?
104
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
• What regular expression matches letter grades such as A,
B+, or D- ?
105
Escape sequences
108
PHP form validation w/ regexes
$state = $_REQUEST["state"];
if (!preg_match("/[A-Z]{2}/", $state)) {
?>
<h2>Error, invalid state submitted.</h2>
<?php
}
PHP
109
• 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;
?>
110
<?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;
?>
111
Cont..
• Using the preg_match function()
• preg_match() is a case sensitiv 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.
112
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,
dash, dot, comma, semicolons, double and
sigle quotes. You can add any character that
you think may be part of an address(+).
113