PHP Xingquan Hill Zhu xqzhucse fau edu PHP

  • Slides: 32
Download presentation
PHP Xingquan (Hill) Zhu xqzhu@cse. fau. edu PHP 1

PHP Xingquan (Hill) Zhu xqzhu@cse. fau. edu PHP 1

PHP q PHP overview q PHP General Syntactic Characteristics q PHP output to browser

PHP q PHP overview q PHP General Syntactic Characteristics q PHP output to browser q Primitives, Operations, and Expressions q Control Statement q Array q Function q File access q Cookie q Session q Form process PHP 2

Origins and use of PHP q Origins v Rasmus Lerdorf – 1994 • Developed

Origins and use of PHP q Origins v Rasmus Lerdorf – 1994 • Developed to allow him to track visitors to his Web site v v An open-source product An acronym for Personal Home Page, or PHP: Hypertext Preprocessor q PHP is a server-side scripting language whose scripts are embedded in HTML documents v Similar to Java. Script, but on the server side q Used form handling, file processing, and database access PHP 3

Origins and use of PHP q PHP is “A” server-side scripting language v One

Origins and use of PHP q PHP is “A” server-side scripting language v One of an alternative to CGI, ASP. NET (Active server pages), and JSP (Java Server Pages) q The PHP processor has two modes: v copy (XHTML) and interpret (PHP) q PHP syntax is similar to that of Java. Script q PHP is dynamically typed q PHP is a interpreted language v Programs may be executed from source form v Each instruction is immediately translated and acted upon by the computer PHP 4

General Syntactic Characteristics q PHP code can be specified in an XHTML document internally

General Syntactic Characteristics q PHP code can be specified in an XHTML document internally or externally: v v v myphp. php Internally: <? php. . . ? > Can appear almost everywhere Externally: include ("my. Script. inc") • The included file can have both PHP and XHTML, if the file has PHP, the PHP must be in <? php. . ? >, even if the include is already in <? php. . ? > – Variable conflict q PHP mode of operation v Copy mode v Interpret mode q Every variable name begin with a $ v Case sensitive v A letter or an underscore followed by any number of letters, digits, or underscores. PHP 5

General Syntactic Characteristics q Comments - three different kinds (Java and Perl) //. .

General Syntactic Characteristics q Comments - three different kinds (Java and Perl) //. . . #. . . /*. . . */ q Statements are terminated with semicolons q Compound statements are formed with braces v Unless used as the body of a function definition, compound statements cannot be blocks (cannot define locally scoped variables) PHP 6

Output q Output from a PHP script is HTML that is sent to the

Output q Output from a PHP script is HTML that is sent to the browser q HTML is sent to the browser through standard output q There are three ways to produce output: echo, print, and printf echo and print take a string, but will coerce other values to strings $name=“John”; $age=20; v echo “$name“, “$age”; (any number of parameters) v echo(“my name: $name, my age: $age”); (only one) v print “$name and $age"; v print (“my name: $name, my age: $age”); v printf(“my name: %s, my age: %s”, $name, $age); v q Echo does not return a value; print return 1 or 0; printf returns the length of the outputted string Output. php PHP 7

Var_dump q Dumps information about a variable v $var 1=3. 1; • Var_dump($var 1);

Var_dump q Dumps information about a variable v $var 1=3. 1; • Var_dump($var 1); • Float(3. 1); v $var 2=“ 3. 1”; • Var_dump($var 2); • String(“ 3. 2”); PHP 8

PHP q PHP overview q PHP General Syntactic Characteristics q PHP Output to browser

PHP q PHP overview q PHP General Syntactic Characteristics q PHP Output to browser q Primitives, Operations, and Expressions q Control Statement q Array q Function q File access q Cookie q Session q Form process PHP 9

Primitives, Operations, and Expressions q Variables primitive. php v No type declarations v An

Primitives, Operations, and Expressions q Variables primitive. php v No type declarations v An unassigned (unbound) variable has the value: NULL v The unset function sets a variable to NULL v The Is. Set function is used to determine whether a variable is NULL v error_reporting(15); - prevents PHP from using unbound variables q PHP has many predefined variables, including the environment variables of the host operating system v You can get a list of the predefined variables by calling phpinfo() in a script PHP 10

Primitives, Operations, and Expressions q There are eight primitive types: v Four scalar types:

Primitives, Operations, and Expressions q There are eight primitive types: v Four scalar types: Boolean, integer, double, and string v Two compound types: array and object v Two special types: resource and NULL PHP 11

Primitives, Operations, and Expressions q Strings string. php v Characters are single bytes v

Primitives, Operations, and Expressions q Strings string. php v Characters are single bytes v The length of a string is limited only by the available memory v String literals use single or double quotes • Single-quoted string literals – Embedded variables are NOT interpolated – Embedded escape sequences are NOT recognized • Double-quoted string literals – Embedded variables ARE interpolated – If there is a variable name in a double quoted string but you don’t want it interpolated, it must be backslashed – Embedded escape sequences ARE recognized v v For both single- and double-quoted literal strings, embedded delimiters must be backslashed String character access • $str=“Apple” • $str{2}=“p” PHP 12

Primitives, Operations, and Expressions q Boolean boolean. php v values are true and false

Primitives, Operations, and Expressions q Boolean boolean. php v values are true and false (case insensitive) v 0 and "" and "0" are false; others are true • But “ 0. 0” is true q Arithmetic Operators and Expressions v Usual operators v If the result of integer division is not an integer, a double is returned v Any integer operation that results in overflow produces a double v The modulus operator coerces its operands to integer, if necessary q Arithmetic functions v floor, ceil, round, abs, min, max, rand, etc. • Round($val, x); PHP 13

Primitives, Operations, and Expressions q Scalar Type Conversions v String to numeric conversion. php

Primitives, Operations, and Expressions q Scalar Type Conversions v String to numeric conversion. php • If the string contains an e or an E, it is converted to double; otherwise to integer • If the string does not begin with a sign or a digit, zero is used q Explicit conversions – casts v e. g. , (int)$total or intval($total) or settype($total, "integer") • Intval($total), doubleval($total), strval($total); q The type of a variable can be determined with gettype or is_type v v gettype($total) - it may return "unknown" is_integer($total) – a predicate function • is_double(), is_bool(), is_string() PHP 14

PHP q PHP overview q PHP General Syntactic Characteristics q PHP Output to browser

PHP q PHP overview q PHP General Syntactic Characteristics q PHP Output to browser q Primitives, Operations, and Expressions q Control Statement q Array q Function q File access q Cookie q Session q Form process PHP 15

Control Statement q Control Expressions v Relational operators - same as Java. Script •

Control Statement q Control Expressions v Relational operators - same as Java. Script • >, <, >=, <=, !=, == v Boolean operators • And, or, xor, !, &&, and || q Selection statements v if, else v switch - as in C • The switch expression type must be integer, double, or string q Loop statements v while - just like C v do-while - just like C v foreach - discussed later PHP 16

Control Statement q break v in any for, foreach, while, do-while, or switch q

Control Statement q break v in any for, foreach, while, do-while, or switch q continue v in any loop q Alternative compound delimiters – more readability if(. . . ): . . . endif; Powers. php PHP 17

Intermingle q XHTML can be intermingled with PHP <? php Intermingle. php $a =

Intermingle q XHTML can be intermingled with PHP <? php Intermingle. php $a = 7; $b = 7; if ($a == $b) { $a = 3 * $a; ? > At this point, $a and $b are equal So, we change $a to three times $a <? php } ? > PHP 18

PHP q PHP overview q PHP General Syntactic Characteristics q PHP Output to browser

PHP q PHP overview q PHP General Syntactic Characteristics q PHP Output to browser q Primitives, Operations, and Expressions q Control Statement q Array q Function q File access q Cookie q Session q Form process PHP 19

Array q A PHP array is really a mapping of keys to values, where

Array q A PHP array is really a mapping of keys to values, where the keys can be numbers or strings q Array creation v Use the array() construct, which takes one or more key => value pairs as parameters and returns an array of them • The keys are non-negative integer literals or string literals • The values can be anything e. g. , $list = array(0 => "apples", 1 => "oranges", 2 => "grapes") • This is a “regular” array of strings v v v If a key is omitted and there have been integer keys, the default key will be the largest current key + 1 If a key is omitted and there have been no integer keys, 0 is the default key If a key appears that has already appeared, the new value will overwrite the old one PHP 20

Array q Arrays can have mixed kinds of elements v e. g. , $list

Array q Arrays can have mixed kinds of elements v e. g. , $list = array("make" => "Cessna", "model" => "C 210", "year" => 1960, 3 => "sold"); $list = array(1, 3, 5, 7, 9); $list = array(5, 3 => 7, 5 => 10, "month" => "May"); $colors = array('red', 'blue', 'green', 'yellow'); Array. php PHP 21

Access Array q Accessing array elements – use brackets v $list[4] = 7; v

Access Array q Accessing array elements – use brackets v $list[4] = 7; v $list["day"] = "Tuesday"; v $list[] = 17; q If an element with the specified key does not exist, it is created v Where? ? q If the array does not exist, the array is created q The keys or values can be extracted from an array v $highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67, "Thu" => 62, "Fri" => 65); v $days = array_keys($highs); v $temps = array_values($highs); arraykey. php PHP 22

Dealing with Arrays q An array can be deleted with unset v unset($list); v

Dealing with Arrays q An array can be deleted with unset v unset($list); v unset($list[4]); # No index 4 element now q is_array($list) v returns true if $list is an array q in_array(17, $list) v returns true if 17 is an element of $list q explode(" ", $str) creates an array with the values of the words from $str, split on a space q implode(" ", $list) creates a string of the elements from $list, separated by a space Explode. php PHP 23

Sequential access to array elements q current and next • • • accessarray. php

Sequential access to array elements q current and next • • • accessarray. php $colors = array("Blue", "red", "green", "yellow"); $color = current($colors); print("$color "); while ($color = next($colors)) print ("$color "); q foreach (array_name as scalar_name) {. . . } • foreach ($colors as $color) { print "Is $color your favorite color? "; } Is Is red your favorite color? blue your favorite color? green your favorite color? yellow your favorite color? PHP 24

Sequential access to array elements q foreach can iterate through both keys and values:

Sequential access to array elements q foreach can iterate through both keys and values: v foreach ($colors as $key => $color) { … } q Inside the compound statement, both $key and $color are defined $ages = array("Bob" => 42, "Mary" => 43); v foreach ($ages as $name => $age) print("$name is $age years old "); v Keyarray. php PHP 25

Viewing Client/Server Environment variables q Environment variables phpinfo. php v Provide information about execution

Viewing Client/Server Environment variables q Environment variables phpinfo. php v Provide information about execution environment • Type of web browser • Type of server • Details of HTTP connection v Stored as array in PHP • $_ENV PHP 26

PHP q q q PHP overview PHP General Syntactic Characteristics PHP Output to browser

PHP q q q PHP overview PHP General Syntactic Characteristics PHP Output to browser Primitives, Operations, and Expressions Control Statement Array Function File access Cookie Session Form process PHP 27

User-Defined Functions q Syntactic form: function_name(formal_parameters) { … } q General Characteristics v Functions

User-Defined Functions q Syntactic form: function_name(formal_parameters) { … } q General Characteristics v Functions need not be defined before they are called (in PHP 3, they must) v Functions can have a variable number of parameters v Function names are NOT case sensitive v Overloading is not permitted v The return function is used to return a value • If there is no return, there is no returned value PHP 28

User-Defined Functions q Parameters v If the caller sends too many actual parameters, the

User-Defined Functions q Parameters v If the caller sends too many actual parameters, the subprogram ignores the extra ones v If the caller does not send enough parameters, the unmatched formal parameters are unbound v The default parameter passing method is pass by value (oneway communication) parameters. php v To specify pass-by-reference, precede an ampersand to the formal parameter function add. One(&$param) { $param++; } $it = 16; add. One($it); // $it is now 17 PHP 29

User-Defined Functions q Parameters v If the function does not specify its parameter to

User-Defined Functions q Parameters v If the function does not specify its parameter to be pass by reference, you can precede an ampersand to the actual parameter and still get pass-by-reference semantics function sub. One($param) { $param--; } $it = 16; sub. One(&$it); // $it is now 15 q Return Values v Any type may be returned, including objects and arrays, using the return • If a function returns a reference, the name of the function must have a prepended ampersand • function &new. Array($x) { … } PHP 30

User-Defined Function q The Scope of Variables scope. php v An undeclared variable in

User-Defined Function q The Scope of Variables scope. php v An undeclared variable in a function has the scope of the function v If you do want to access a nonlocal variable, it must be declared to be global, as in global $sum; q The Lifetime of Variables static. php v Normally, the lifetime of a variable in a function is from its first appearance to the end of the function’s execution static $sum = 0; # $sum is static Its lifetime begins when the variable is first used in the first execution of the function, ends when the script execution ends. (browser leaves the document in which the php script is embedded) PHP 31

PHP q q q PHP overview PHP General Syntactic Characteristics PHP Output to browser

PHP q q q PHP overview PHP General Syntactic Characteristics PHP Output to browser Primitives, Operations, and Expressions Control Statement Array Function File access Cookie Session Form process PHP 32