Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  Originally Personal Home Page  PHP is interpreted  PHP code is embedded.

Similar presentations


Presentation on theme: "PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  Originally Personal Home Page  PHP is interpreted  PHP code is embedded."— Presentation transcript:

1 PHP Server-side Programming

2 PHP  PHP stands for PHP: Hypertext Preprocessor  Originally Personal Home Page  PHP is interpreted  PHP code is embedded into HTML code  interpreter is invoked by the web server  Syntax is similar to C, Java, Perl etc.  Think of a cross between perl and C  PHP is open source, free, available for most platforms, popular

3 What can you do with PHP  Generate content as an HTML page is loaded (generate HTML code)  User sees only the generated code, not your PHP code  Respond to a form with dynamic content  Retrieve and display information from a database or server-side files

4 Where does the PHP code go?  PHP code goes into a special element type in your HTML files.  You can have multiple php elements in a page  Code in the php element is sent to the php interpreter; everything else is assumed to be content  File needs to have a.php or.phtml extension

5 HelloWorld in PHP PHP

6 Basics  Syntax is similar to C and perl  Comments  //  /* */  #  Statements are terminated by semicolon  { … } is compound statement, not a block  Whitespace insensitive  Reserved words, function names are case- insensitive

7 More Basics  Variable names (case-sensitive) same as for Java with a $ in front  can be assigned by value or by reference  Dynamically typed  For output use  echo  print  printf just like in C

8 Here Documents  Instead of using multiple print statements, use a here document print <<<_HTML_ … _HTML_  Everything between the two _HTML_ is printed

9 Built-In Types  Primitive  boolean  integer  float  string  Compound  array (similar to hash in perl)  object - defined by a class  Special types  NULL  resource

10 Strings  Use either double or single quotes for strings  In single-quoted strings, all characters are interpreted literally  Variables and escape characters are interpreted in double-quoted strings  Strings can extend over multiple lines

11 String functions  trim removes leading and trailing whitespace  ltrim and chop remove from one end  strlen gives number of characters in the string  == can be used to compare strings (case sensitive)  strcasecmp() compares strings ignoring case (semantics of C strcmp)  Use. for concatenation  get substrings using substr( string, start, length)

12 Numbers  PHP distinguishes between integer and floating point values  Usual set of arithmetic operations and assignment operators  integer division can give floating point result  % coerces operands to integers  Usual set of mathematical functions  Other functions for things like formatting, type conversion, …

13 Booleans  False values are 0, 0.0, "0", "", false, NULL, array with 0 elements, object with 0 member variables  everything else is true  Usual set of comparison operators  ( = >)  work with strings  Usual set of logical operators (! && ||) plus and or xor

14 Type Conversions  Coercion (automatic type conversion) happens based on context. It happens in more ways than in Java.  integer -> double  numeric, boolean -> string  double -> integer  numeric -> boolean  string -> numeric  Explicit type conversion (int)$sum intval($sum) settype($sum, "integer")

15 Control Statements  Selection if ( cond) { … } elseif (cond2) { …} … else { … }  also switch  Loops while (cond) { … } do { … } while( cond); for (init; cond; update) { … } foreach() { … }

16 Declaring Functions  function functionName(paramList) {  /* code goes here */ }  paramList is comma-separated list of param names with optional default values  parameters with default values need to be at the end of the list  use return to return a value  functions can be nested in PHP

17 Calling Functions  functionName( argList)  argList is comma-separated list of expressions  number of arguments needs to match the number of parameters unless default values have been assigned  if the last n parameters have default values, you can omit the last 1, 2,.. n arguments  you can't skip a position in the argument list

18 Variable scope  Variables defined outside of any function are global  Variables defined inside a function are local to the function (as are parameters)  To use global variables in a function  get them from $GLOBALS, an array containing all global variables x = $GLOBALS['varname'];  use the global keyword to declare them to be global global $varname;

19 Compound Types in PHP  PHP has two compound types  Arrays -arrays in PHP are really ordered maps (hash tables)  multi-dimensional arrays are arrays whose elements are arrays  Objects - variables whose type is defined by a class

20 Arrays  An array consists of a collection of elements  each element has a key and a value (like a hash table)  arrays with only numeric keys are a special case  you can use arrays with numeric keys the same way you do an array in C or Java

21 Creating an array  Create dynamically by assigning values to elements  $veggie['corn'] = 'yellow';  $dinner[0] = 'Lemon Chicken';  Use the Array constructor  $veggie = array( 'corn' => 'yellow', 'beet' => 'red', 'carrot' => 'orange');

22 Creating a numeric array  Use array with just a list of values  keys will automatically be numbers (starting from 0) $dinner = ('Sweet Corn and Asparagus', 'Lemon Chicken', 'Spicy Eggplant');  Add new elements to end of list by assigning with no index  $dinner[] = 'Braised Bamboo fungus';

23 Using arrays  count($arrayName) gives the number of elements in the array  implode(delim, array) creates a string from an array  $menu = implode( ', ', $dinner);  explode(delim, string) creates a numeric array from a string  $dinner = explode( ', ', $menu);

24 Sorting arrays  The array elements will be rearranged by these methods  sort() / rsort() sort by element values (ascending/descending)  keys become numeric  asort() / arsort() sort by element value, keeping keys and values together  ksort() / krsort() sort by key, keeping keys and values together

25 Looping with arrays  Use foreach to loop through elements of array foreach( $meal as $key => $value) print "$key $value\n"; foreach( $dinner as $dish) print "You can eat $dish.\n"  foreach goes through elements in order they were added to array  not necessarily numeric order

26 Using arrays as lists and stacks  The functions current, next, prev, reset (which take an array parameter) allow you to use an array like a linked list.  list order is the order of insertion  array_push and array_pop allow you to use an array for a stack

27 Classes and Objects  PHP supports object-oriented programming  Class is a template describing both data and operations  Method is a function defined in a class  Property is a variable defined in a class  Constructor is used to create instances (objects)  Static method doesn't need an object

28 Sample Class definition class Cart { var $items; // Items in our shopping cart // Add $num articles of $artnr to the cart function add_item($artnr, $num) { $this->items[$artnr] += $num;} // Take $num articles of $artnr out of the cart function remove_item($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } elseif ($this->items[$artnr] == $num) { unset($this->items[$artnr]); return true; } else { return false; } }

29 Constructors  Constructor is a method with the same name as the class  Use it to initialize properties class Item { var $catalogNum, $price; function Item($id='none', $cost='0.0') { $catalogNum=$id; $price = $cost; } … }

30 Using Objects  Use new to create objects  $myItem = new Item( 'AB234', 3.95);  Access methods and properties with -> operator  $charge = $myItem->price;

31 Regular Expressions  PHP has POSIX regular expressions built in  The PCRE module allows you to use Perl compatible regular expressions  preg_match takes a pattern and a string and returns true or false  preg_split takes a delimiter and a string and returns an array

32 Running Shell Commands  PHP provides the shell_exec() function for running an external program from the php program $filelist = shell_exec( 'ls');  If you are passing form input on to another program, use escapeshellargs() to clean it up first

33 Extensions  The mycrypt extension to PHP provides a number of standard encryption algorithms  The Perl and Java extensions allow you to execute code written in those languages from your PHP program  PEAR is an extension that is useful for applications that use databases  more next time

34 Sources  Learning PHP 5 by David Sklar  Programming the World Wide Web by Robert Sebesta  Programming PHP by Rasmus Ledorf and Kevin Tatroe  PHP home page  http://www.php.net/


Download ppt "PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  Originally Personal Home Page  PHP is interpreted  PHP code is embedded."

Similar presentations


Ads by Google