Upload
tech2click
View
222
Download
0
Embed Size (px)
Citation preview
8/7/2019 Introduction to PHP Part.1
1/39
Introduction to PHPPart.1Chapter 9 from text book
1
8/7/2019 Introduction to PHP Part.1
2/39
Outline
Server-Side Basics
PHP Basic Syntax
Data Types
Control Structures
Arrays
Embedded PHP
Advanced PHP Syntax
Functions
Variable Scope
2
8/7/2019 Introduction to PHP Part.1
3/39
Do you want to build a website like:
3http://builtwith.com
8/7/2019 Introduction to PHP Part.1
4/39
Server-Side Basics
some URLs actually specify programs that the web
server should run, and then send their output back toyou as the result: http://www.ksu.edu.sa/Pages/default.aspx
the above URL tells the server ksu.edu.sa to run the programdefault.aspx and send back its output
4
BrowserPresentation
TierDatabase
Web Server
Logic Tier
Three-Tier
http://www.ksu.edu.sa/Pages/default.aspxhttp://www.ksu.edu.sa/Pages/default.aspx8/7/2019 Introduction to PHP Part.1
5/39
Server-Side Web Programming
Server-side pages are programs written usingone of many web programming languages/frameworks examples: PHP, Java/JSP, Ruby on Rails, ASP.NET,
Python, Perl
The web server contains software thatallows it to run those programs and sendback their output as responses to webrequests
5
8/7/2019 Introduction to PHP Part.1
6/39
What is PHP?
PHP stands for "PHP HypertextPreprocessor"
A server-side scripting language
Used to make web pages dynamic: Provide different content depending on context
Interface with other services: database, e-mail, etc
Authenticate users
Process form information PHP code can be embedded in XHTML
code
6
8/7/2019 Introduction to PHP Part.1
7/39
Lifecycle of a PHP web request
7
Browser requests a .html file (static content): server just sends that file
Browser requests a .php file (dynamic content): server reads it, runs
any script code inside it, then sends result across the network
-script produces output that becomes the response sent back
8/7/2019 Introduction to PHP Part.1
8/39
Hello, World!
The following contents could go into a file hello.php:
8
Hello, world!
A block or file of PHP code begins with
PHP statements, function declarations, etc. appear between theseendpoints
8/7/2019 Introduction to PHP Part.1
9/39
Viewing PHP output
You can't view your .php page on your local hard drive; you'll either see
nothing or see the PHP source code
if you upload the file to a PHP-enabled web server, requesting the .php
file will run the program and send you back its output
9
8/7/2019 Introduction to PHP Part.1
10/39
PHP Syntax Template
HTML content
HTML content
HTML content ...
10
Any contents of a .php file between areexecuted as PHP code
All other contents are output as pure HTML
PHP statements are terminated with semicolons
8/7/2019 Introduction to PHP Part.1
11/39
Console Output: print
print "Hello, World!\n";
print "Escape \"chars\" are the SAME as
in Java!\n";
print "You can have line breaks in a
string.";
11
Syntax:print text;
Hello, World! Escape "chars" are the SAME as in Java! You can have line
breaks in a string.
Some PHP programmers use the equivalentecho instead of print
8/7/2019 Introduction to PHP Part.1
12/39
Comments
// single-line comment
# single-line comment
/*
multi-line comment
*/
12
8/7/2019 Introduction to PHP Part.1
13/39
Variables
Syntax:$name = expression;
13
$user_name = Amal Ahmad";
$age = 13;
$College_age= $age + 5;
$this_class_is_useful= TRUE; Names are case sensitive; keywords and function names are not
case sensitive.
Names always begin with $, on both declaration and usage
Always implicitly declared by assignment (type is not written) A loosely typed language (like JavaScript)
A variable that has not been assigned a value is unbound and has
the value NULL
IsSet($x) function, checks if the variable $x is set to a value or
not.
8/7/2019 Introduction to PHP Part.1
14/39
Types
Basic types: int, float, boolean, string, array, object, NULL
Type can be determined with the gettype function and
with the is_int function and similar functions for
other types
Type conversions can be forced in three ways
(int)$sum
intval($sum) using several conversion functions
settype($x, integer)
14
8/7/2019 Introduction to PHP Part.1
15/39
Types
Implicit type conversions as demanded by thecontext in which an expression appears
A string is converted to an integer if a
numeric value is required and the string startswith a digit or a sign.
A string is converted to a double if a numeric
value is required and the string is a valid
double literal (including either a period or eor E)
15
8/7/2019 Introduction to PHP Part.1
16/39
String Type
$favorite_color= Black";
print $favorite_color[2]; // a
16
Zero-based indexing using bracket notation
There is no char type; each letter is itself a String String concatenation operator is . (period), not+
- 5 + "2 nice books" === 7
- 5 . "2 nice books " === "52 nice books "
Can be specified with " " or ' '
8/7/2019 Introduction to PHP Part.1
17/39
Interpreted strings
$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n";
//You are 16 years old.
17
Strings inside " " are interpreted
- variables that appear inside them will have their values
inserted into the string
Strings inside ' ' are not interpreted:
print 'You are $age years old.\n';
//You are $age years old.\n
8/7/2019 Introduction to PHP Part.1
18/39
String functions
18
8/7/2019 Introduction to PHP Part.1
19/39
bool (Boolean) Type
$feels_like_summer = TRUE;
$php_is_bad = FALSE;
$student_count = 217;
$nonzero = (bool) $student_count; // TRUE
19
The following values are considered to be FALSE (all others
are TRUE):
- 0 and 0.0 (but NOT 0.00 or 0.000)
- "", "0", and NULL (includes unset variables)
- Arrays with 0 elements Can cast to booleanusing (bool)
FALSE prints as an empty string (no output); TRUE prints as 1 TRUE and FALSE keywords are case insensitive
8/7/2019 Introduction to PHP Part.1
20/39
int and float Types
$a = 7 / 2; // float: 3.5
$b = (int) $a; // int: 3
$c = round($a); // float: 4.0
$d = "123"; // string: "123"
$e = (int) $d; // int: 123
20
Int for integers and float for reals
Division between two int values can produce a float
8/7/2019 Introduction to PHP Part.1
21/39
Math operations
21
the syntax for method calls, parameters,
returns is the same as Java
8/7/2019 Introduction to PHP Part.1
22/39
Relational Operators
PHP has the usual comparison operators: >,
8/7/2019 Introduction to PHP Part.1
23/39
Boolean Operators
PHP supports &&, || and ! as inC/C++/Java
The lower precedence version and and
or are provided The xor operator is also provided
23
8/7/2019 Introduction to PHP Part.1
24/39
if/else Statement
if (condition) {
statements;
} elseif(condition) {
statements;
} else {
statements;
}
24
NOTE: although elseif keyword is much more common,
else if is also supported
8/7/2019 Introduction to PHP Part.1
25/39
for loop (same as Java)
for (initialization; condition; update) {
statements;
}
25
for ($i = 0; $i < 10; $i++) {
print "$i squared is " . $i * $i . ".\n";
}
8/7/2019 Introduction to PHP Part.1
26/39
while loop (same as Java)
while (condition) {
statements;
}
26
do {
statements;
} while (condition);
break and continue keywords also behave as inJava
8/7/2019 Introduction to PHP Part.1
27/39
Arrays
Arrays in PHP combine the characteristicsof regular arrays and hashes
An array can have elements indexed numerically.
These are maintained in order An array, even the same array, can have elements
indexed by string. These are not maintained in
any particular order
The elements of an array are, conceptually,
key/value pairs
27
8/7/2019 Introduction to PHP Part.1
28/39
Array Creation
Two ways of creating an array $a = array(); // empty array (length 0)
Assigning a value to an element of an array,e.g. $a[0]=7; // one element
Create a numerically indexed array$list =array(23, xiv, bob, 777);
Create an array with string indexes $a = array(a =>apple, o =>orange)
Array elements are accessed by using a subscript insquare brackets.
To append, use bracket notation without specifying anindex
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!"; // add string to end (at index 5)
28
8/7/2019 Introduction to PHP Part.1
29/39
Array functions
29
8/7/2019 Introduction to PHP Part.1
30/39
Functions for Dealing with Arrays
$cites = array(Makkah, Madeena, Riyadh,Khubar);
unset($cites[2]); // removes Riyadh
$x = array_keys($cities); // returns 0,1,3
$y = array_values($cities); // returns Makkah,
Madeena, Khubararray_key_exists(2, $cites); //returns false
$words = explode( ,This is a string); // returns
anarray consists of 4 elements This, is, a,
string
$str = implode( , $cites ); // returns a string
MakkahMadeenaKhubar
30
8/7/2019 Introduction to PHP Part.1
31/39
Sequential Access to Array
Elements PHP maintains a marker in each array, called the current
pointer Several functions in PHP manipulate the current pointer
The pointer starts at the first element when the array is created
The next function moves the pointer to the nextelement and returns the value there
31
$cites = array(Makkah, Madeena, Riyadh,
Khubar);
$city = current($cities);
print ($city - );
While ($city = next($cities))
print ($city - );
Makkah - Madeena - RiyadhKhubar-
8/7/2019 Introduction to PHP Part.1
32/39
Sequential Access to Array Elements
The each function move the pointer to the nextelement and returns the key/value pair at the previousposition The key and value can be accessed using the keys key and
value on the key/value pair
32
$cites = array(Makkah => 45, Madeena => 48,
Riyadh => 50, Khubar => 43);
While ($city = each($cities)){
$name = $city[key];
$temp = $city[value]
print (The temperature of $city is $temp
);}
The temperature of Makkah is 45
The temperature of Madeena is 48
The temperature of Riyadh is 50
The temperature of Khubar is 43
8/7/2019 Introduction to PHP Part.1
33/39
Sequential Access to Array Elements
next and currentfunctions return false ifno more elements are available
prev moves the pointer back towards thebeginning of the array
reset moves the pointer to the beginning ofthe array
PHP provides the array_push function that
appends its arguments to a given array
The function array_pop removes the lastelement of a given array and returns it
33
8/7/2019 Introduction to PHP Part.1
34/39
Iterating Through an Array
The foreach statement has two forms for iterating throughan array
foreach (arrayas scalar_variable) loopbody
foreach (arrayas key => value) loop body
The first version assigns each value in the array to thescalar_variable in turn
The second version assigns each key to key and theassociated value to value in turn
In this example, each day and temperature is printed
$lows = array("Mon" => 23, "Tue" => 18, "Wed"=> 27);
foreach ($lows as $day => $temp)
print("The low temperature on $day was $temp
");
34
8/7/2019 Introduction to PHP Part.1
35/39
Embedding code in web pages
most PHP programs actually produce HTML astheir output
dynamic pages; responses to HTML form submissions;
etc.
an embedded PHP program is a file that
contains a mixture of HTML and PHP code
35
8/7/2019 Introduction to PHP Part.1
36/39
Printing HTML tags in PHP = bad
style
8/7/2019 Introduction to PHP Part.1
37/39
Functions
Function syntax:function name([parameters]) {...}
The parameters are optional, but not theparentheses
Function names are case insensitive A return statement causes the function to
immediately terminate and return a value, if any,provided in the return A function that reaches the end of the body
without executing a return, returns no value
37
8/7/2019 Introduction to PHP Part.1
38/39
Parameters
A formal parameter, specified in a functiondeclaration, is simply a variable name If more actual parameters are supplied in a call than
there are formal parameters, the extra values areignored
If more formal parameters are specified than thereare actual parameters in a call then the extra formalparameters receive no value
PHP defaults to pass by value
Putting an ampersand & in front of a formal parameterspecifies that pass-by-reference
An ampersand can also be appended to the actualparameter (which must be a variable name)
38
8/7/2019 Introduction to PHP Part.1
39/39
Variable scope
$Last_Name = ""; // global
...
function myFunc() {
global $Last_Name;
$first_Name= Norah"; // local
$Last_Name = $Last_Name $first_Name;
print " $Last_Name ";
}
Variables declared in a function are local to that function Variables not declared in a function are global
If a function wants to use a global variable, it must have a
global statement