360 likes | 627 Views
PHP. Server-side Programming. 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
E N D
PHP Server-side Programming
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
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
Where does the PHP code go? • PHP code goes into a special element type in your HTML files. <?php … ?> • 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
HelloWorld in PHP <html> <head> <title>PHP</title> </head> <body> <?php echo 'Hello, world!' ?> </body> </html>
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
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
Here Documents • Instead of using multiple print statements, use a here document print <<<_HTML_ <html><head> … </head> <body> … </body></html> _HTML_ • Everything between the two _HTML_ is printed
Primitive boolean integer float string Compound array (similar to hash in perl) object - defined by a class Special types NULL resource Built-In Types
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
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)
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, …
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 andorxor
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")
Selection if ( cond) { … } elseif (cond2) { …} … else { … } also switch Loops while (cond) { … } do { … } while( cond); for (init; cond; update) { … } foreach() { … } Control Statements
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
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
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;
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
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
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');
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';
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);
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
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
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
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
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; } }
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; } … }
Using Objects • Use new to create objects • $myItem = new Item( 'AB234', 3.95); • Access methods and properties with -> operator • $charge = $myItem->price;
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
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
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
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/