PHP Guest Lecture by Ari Gilder Parts of

PHP Guest Lecture by Ari Gilder Parts of this lecture adapted from the PHP Manual at http: //www. php. net 1

What is PHP? n n PHP stands for PHP: Hypertext Preprocessor PHP is a scripting language n n n Especially suitable for web development n n Often used server side There are extensions that allow client side as well Can be embedded into HTML, like JSP Developed by Zend Technologies n Most current versions are: 5. 0. 2, 4. 3. 9 2

What can PHP do? n PHP has a tremendous number of built-in libraries, as well as separately downloadable ones n n n n APIs for almost any kind of database Image manipulation functions (using GD library) Encryption functions Regular expressions PDF creation XML parsing Even Java integration! Much, much more… 3

Advantages/Disadvantages n n n PHP is an interpreted language – no compilation needed PHP is intended to serve large audiences, so the Zend Engine is fairly robust (can be enhanced) PHP is easy to learn, and very powerful It’s free! However: PHP 4’s support for OOP is fledgling It’s just a scripting language – not often used for actual desktop applications 4

Using PHP n n n PHP is most often found on UNIX environments There are Windows (and other OS) versions as well Apache and PHP work wonders There are some pre-compiled packages of Apache, PHP and My. SQL available Primarily designed for the Web – mostly any modern browser can recognize PHP n Can also run from command line 5

The hardest program ever. <? php echo “Hello World”; //well, duh print “I can do this too. ”; //look Ma, no parenthesis! ? > 6

Basic Syntax n There a few ways of inserting PHP into HTML: n <? php /* code goes here */ ? > n n <? /* using short tags */ ? > n n n This is the recommended way of inserting PHP Works with XML and XHTML compliant documents Looks like a Processing Instruction Most common method, but requires short_tags option to be enabled <script language=“php”> /* insert PHP code */ </script> <% /* using ASP/JSP-style tags */ %> 7

Comments n There a few acceptable comment styles: n n n /* Using C-style comments */ // Using C++-style comments # Using UNIX-style comments n n The C++ style is recommended, UNIX style discouraged C++ style comments go to the end of the line, or the end of the current block of PHP code. n Hello <? php // ? > World 8

Variables and Types n n PHP variables are usually scalars, like $my. Var There are four scalar types: n n n Two compound types: n n n boolean integer string float array object Two special types: n n resource NULL 9

Variables and Types, II n Casting: n n Typing: n n (string) 50 will evaluate as “ 50” settype($my. Int, “string”) sets the type of $my. Int to a string Identity comparison: n n If $a=50 and $b=“ 50”, then $a == $b However, !($a === $b), or, $a !== $b 10

Variable variables n A rather useful feature, much like pointers in C $message = “PHP rocks”; $a = $message; //$a == “PHP rocks” $b = “message”; echo $$b; //prints “PHP rocks” $my. String = “average”; //can have variable $func = “my. String”; //functions too! echo $$func(0, 1); //prints out 0. 5 11

Operators n n PHP has more or less the same set of operators as C or Java Some new ones: n n n . is the concatenation operator === is identity comparison @ is error suppression (legal before any expression) n n Won’t suppress parse errors `$command` is the shell execution operator (``) n n n Will run $command at the shell; return value is command output Disabled in PHP Safe Mode Be VERY, VERY CAREFUL with its use!!! 12

Control Structures n Same control structures as Java, plus a few more n declare(directive) statement n n foreach($arr as $key=>$val) n n n Used for setting execution directives for a block of code (i. e. ticks) Within the body of the loop, $key and $val are local variables containing the key/value of the current element. Can be used on arrays and objects File inclusion: n n include() or include_once() require() or require_once() n These are language constructs, so they don’t need ()’s 13

Functions n n n Declared using the function keyword, like Java. Script PHP 4 supports both variable number of arguments, as well as default argument values PHP 4 does not support function overloading function foo($arg_1, &$arg_2, /*. . . , */ $arg_n) { echo "Example function. n"; $arg_2 = “new value”; //& passes $arg_2 by ref return $retval; } 14

Functions, II n PHP supports two types of conditional functions: $makefoo=true; //no foo() here, yet if ($makefoo) { function foo() { echo “foo() function only accessible once program execution reaches here. n"; } } function foo() { function bar() { echo "I don't exist until foo() is called. n"; } } //bar() doesn’t exist yet foo(); //now bar() exists bar(); 15

Arrays n Arrays declared using the array() function n n You can assign keys to a value n n Example: $arr = array(“apples”, “bananas”); $arr = array(“red”=>“apples”, “yellow”=>“bananas”); And you can add arrays by the next highest index: $arr = array(1 => “bananas”, 0 => “apples”); $arr[] = “oranges”; //$arr[2] contains oranges n You can delete an element: n unset($arr[2]); //this function works on all vars 16

Array operators n Let’s say $a and $b are arrays: n $a + $b is their union n n Appends the right array to the left array The left array’s keys are not overwritten if there is a conflict $a == $b checks that they have the same elements $a === $b checks they have the same elements, in the same order, and their keys and values are identical Same with $a != $b, $a <> $b, $a !== $b 17

Built-in array functions n Along with its extensive API, PHP has a vast number of functions for operating on arrays n n Sorting functions: sort(), rsort(), krsort(), arsort(), uksort(), uasort() in_array($needle, $haystack, true) n n Checks if $needle is in array $haystack, and makes sure types are equal (third parameter default is false) count($arr) returns length of the array_pop(), array_push(), array_rand() array_multisort() n n Sorts multiple arrays in tandem, or multi-dimensional arrays Weirdest function I know – often works how you want, though 18
![Some other useful API functions n date($format [, $timestamp]) n n n $format is Some other useful API functions n date($format [, $timestamp]) n n n $format is](http://slidetodoc.com/presentation_image_h2/fc1c86ed471d0b8031260f4ca966a5f5/image-19.jpg)
Some other useful API functions n date($format [, $timestamp]) n n n $format is a string composed from the formatting components listed in the PHP manual If $timestamp is not present, it defaults to time() (the current UNIX timestamp) define(“THE_ANSWER”, 42) is_array(), is_bool(), is_file(), is_int(), etc. phpinfo() n n Prints out PHP information, compiled libraries Very useful diagnostic tool for checking GET/POST values 19

Some useful String functions n implode($glue, $arr) n n explode($sep, $str) n n Opposite of implode – splits a string into an array nl 2 br($str) n n Fuses the elements of $arr with $glue as a separator Converts newlines in a string to tags strstr($haystack, $needle) n Returns substring starting from first occurrence of $needle till the end of $haystack, or false if not found 20

Interacting with HTML n n n PHP can generate an HTML file which the client views Since PHP is server-side, all the PHP code is executed first, and the only output is HTML (or binary. . . ) You can print out variable contents in the HTML: n n n <input type=“text” name=“user” value=“<? =$user? >”> Part of doing that requires actually processing data! How do we get data from an HTML form? 21

Sample HTML Form – login. html <html> <body> <form method=“POST” action=“login. php”> User name: <input type=“text” name=“user” /> Password: <input type=“password” name=“pass” /> <input type=“submit” /> </form> </body> </html> 22
![Processing script – login. php <? php if(empty($_POST[“user”]) || empty($_POST[“pass”]) { die(“You didn’t enter Processing script – login. php <? php if(empty($_POST[“user”]) || empty($_POST[“pass”]) { die(“You didn’t enter](http://slidetodoc.com/presentation_image_h2/fc1c86ed471d0b8031260f4ca966a5f5/image-23.jpg)
Processing script – login. php <? php if(empty($_POST[“user”]) || empty($_POST[“pass”]) { die(“You didn’t enter a user and a password!”); } if(lookup_user($_POST[“user”], $_POST[“pass”])) { echo “Welcome to the administration. ”; include “adminfile. php”; } else { die(“Bad user or password error. ”); } ? > 23
![Superglobals n What’s this $_POST[“user”] thing? n n n $_POST is a superglobal array, Superglobals n What’s this $_POST[“user”] thing? n n n $_POST is a superglobal array,](http://slidetodoc.com/presentation_image_h2/fc1c86ed471d0b8031260f4ca966a5f5/image-24.jpg)
Superglobals n What’s this $_POST[“user”] thing? n n n $_POST is a superglobal array, i. e. it is an array of data passed to the PHP script that is available anywhere in the script. Prior to PHP 4. 1. 0, it used to be $HTTP_POST_VARS There are other superglobal arrays: n n n n $GLOBALS – all variables defined in the global scope $_SERVER – server variables, viewable on phpinfo() $_GET – all form fields or querystrings passed by GET $_COOKIE – all cookie values $_FILES – information about uploaded files $_ENV – environment variables, viewable on phpinfo() $_REQUEST – union of $_GET, $_POST, $_COOKIE (GPC order) $_SESSION – contains session variables 24

Session Tracking n n As in Java Servlets, sessions can be tracked via hidden HTML forms or by cookies PHP also has its own method of session tracking A unique session ID is generated for every user This ID can be propagated across pages in two ways: n n Cookies (most common) URL query string n n Append the predefined constant SID after the ? of a URL method is more prone to security vulnerability 25

Session Tracking, II n n n All session data (besides ID) is stored on the server In order to initialize or continue a session, the best way is to explicitly use the session_start() function at the top of your page. Session variables are accessed or set by $_SESSION n n Example: $_SESSION[“user”] = $_POST[“user”]; Then, on another page, after you call session_start() you can access $_SESSION[“user”] Objects and arrays can be stored in sessions A call to session_destroy() will erase all data from the session 26

Classes and Objects in PHP 4 n n n PHP’s evolution seems to be largely defined by its support for OOP In PHP 4, there are no modifiers (public, private, etc) Classes can be defined anywhere n n But, you can’t break up a class definition (i. e. define a class in one block of PHP and its methods in another block) Single inheritance is supported, but no interfaces No real distinction between static/dynamic methods No destructors 27

Some Object Syntax <? php class A { function A() { echo "I am the constructor of A. n"; } } function B() { echo "I am a regular function named B in class A. n"; echo "I am not a constructor in A. n"; } class B extends A { function C() { echo "I am a regular function. n"; } } // This will call B() as a constructor. $b = new B; //no () required ? > 28

Constructor oddities n n What will be printed from the previous block of code? The answer: it depends. n n In PHP 3: ‘A constructor is a function of the same name as the class. ’ In PHP 4: ‘A constructor is a function of the same name as the class it is being defined in. ’ PHP 5 has an entirely different way of handling constructors Note: neither PHP 3 nor PHP 4 will automatically call the constructors of the base class (Java does) – unless the child class contains no constructor. It is your responsibility to propagate constructor calls upstream 29

Object fields & methods n Fields can be declared at the top of a class definition using the var keyword (i. e. var $internal. Array; ) n n Fields defined with var can only be initialized to constants To access an object field or method: n n $my. Obj->my. Method(42); $my. Obj->my. Var = 5; n n CAUTION: DO NOT say $my. Obj->$my. Var unless you know what you are doing!!! You can also use the scope resolution operator (: : ) to access methods/fields “statically” n Math. Stuff: : std. Dev($array_o_nums); 30

A few other keywords n n The $this variable (just like in Java) The parent keyword (should only be used when defining a class’ methods) n n If B extends A, and both contain a method called example, you can have B: : example() say parent: : example() [which is analogous to A: : example()] The magic functions __sleep() and __wakeup() n n These are used for preparing an object to be serialized or unserialized (like restoring a database connection) Can be overridden if you want specific functionality 31

Some additional features in PHP 5 n n n n n Different syntax for constructors (but backwardscompatible) – looks for __construct() method Allows destructors with a __destruct() method Allows modifiers – public, private, protected Supports static keyword const (fields) and final (methods & classes) keywords Supports interfaces and abstract classes Exceptions Reflection MUCH MORE!!! 32

Database Connectivity n n n PHP supports nearly any type of database on the market Most common database used with PHP is My. SQL Interactions with databases are what make PHP such a powerful language n n Large stores of persistent data Shopping carts, molecule databases, etc. Actions are executed via SQL queries to the database engine I won’t go into much detail… 33
![A Taste of My. SQL n mysql_connect($dbhost, $dbuser, $dbpass […]) n n n mysql_query($query A Taste of My. SQL n mysql_connect($dbhost, $dbuser, $dbpass […]) n n n mysql_query($query](http://slidetodoc.com/presentation_image_h2/fc1c86ed471d0b8031260f4ca966a5f5/image-34.jpg)
A Taste of My. SQL n mysql_connect($dbhost, $dbuser, $dbpass […]) n n n mysql_query($query [, $linkid]) n n Returns a link id resource $dbhost is most often “localhost” Returns a result id resource $query is specified in SQL syntax Example: SELECT * FROM users WHERE username=‘ari’ mysql_fetch_array($result) n n Returns an associative array with keys being field names $result is a result id resource 34

Conclusion n PHP is a very extensive language, with support for a huge number of APIs for databases, XML, images, etc. n n n The old XML parser in PHP 4 is a SAX-like parser PHP 5 introduces Simple. XML for a DOM-like structure PHP also does have APIs for actual DOM, XSL, etc. PHP combines a lot of useful features from various languages (C++/Java/Perl) PHP is weakly-typed, but this also allows for more flexible code n But beware: it also allows for bad coding habits to develop! 35

The End 36
- Slides: 36