PHP Guest Lecture by Ari Gilder Parts of this lecture adapted from the PHP Manual at http://www.php.net 1 What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a scripting language Especially suitable for web development Often used server side There are extensions that allow client side as well Can be embedded into HTML, like JSP Developed by Zend Technologies Most current versions are: 5.0.2, 4.3.9 2 What can PHP do? PHP has a tremendous number of built-in libraries, as well as separately downloadable ones 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 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: PHP4’s support for OOP is fledgling It’s just a scripting language – not often used for actual desktop applications 4 Using PHP 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 MySQL available Primarily designed for the Web – mostly any modern browser can recognize PHP 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 There are a few ways of inserting PHP into HTML: <?php /* code goes here */ ?> <? /* using short tags */ ?> 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 There are a few acceptable comment styles: /* Using C-style comments */ // Using C++-style comments # Using UNIX-style comments 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. Hello <?php // ?> World 8 Variables and Types PHP variables are usually scalars, like $myVar There are four scalar types: Two compound types: boolean integer string float array object Two special types: resource NULL 9 Variables and Types, II Casting: Typing: (string) 50 will evaluate as “50” settype($myInt, “string”) sets the type of $myInt to a string Identity comparison: If $a=50 and $b=“50”, then $a == $b However, !($a === $b), or, $a !== $b 10 Variable variables A rather useful feature, much like pointers in C $message = “PHP rocks”; $a = $message; //$a == “PHP rocks” $b = “message”; echo $$b; //prints “PHP rocks” $myString = “average”; //can have variable $func = “myString”; //functions too! echo $$func(0, 1); //prints out 0.5 11 Operators PHP has more or less the same set of operators as C or Java Some new ones: . is the concatenation operator === is identity comparison @ is error suppression (legal before any expression) Won’t suppress parse errors `$command` is the shell execution operator (``) 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 Same control structures as Java, plus a few more declare(directive) statement foreach($arr as $key=>$val) 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: include() or include_once() require() or require_once() These are language constructs, so they don’t need ()’s 13 Functions Declared using the function keyword, like JavaScript PHP4 supports both variable number of arguments, as well as default argument values PHP4 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 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 Arrays declared using the array() function You can assign keys to a value 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 You can delete an element: unset($arr[2]); //this function works on all vars 16 Array operators Let’s say $a and $b are arrays: $a + $b is their union 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 Along with its extensive API, PHP has a vast number of functions for operating on arrays Sorting functions: sort(), rsort(), ksort(), krsort(), asort(), arsort(), usort(), uksort(), uasort() in_array($needle, $haystack, true) 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 array_pop(), array_push(), array_rand() array_multisort() 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 date($format [, $timestamp]) $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() Prints out PHP information, compiled libraries Very useful diagnostic tool for checking GET/POST values 19 Some useful String functions implode($glue, $arr) explode($sep, $str) Opposite of implode – splits a string into an array nl2br($str) Fuses the elements of $arr with $glue as a separator Converts newlines in a string to <br /> tags strstr($haystack, $needle) Returns substring starting from first occurrence of $needle till the end of $haystack, or false if not found 20 Interacting with HTML 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: <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” /> <br /> Password: <input type=“password” name=“pass” /> <br /> <input type=“submit” /> </form> </body> </html> 22 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 What’s this $_POST[“user”] thing? $_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: $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 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: Cookies (most common) URL query string Append the predefined constant SID after the ? of a URL URL method is more prone to security vulnerability 25 Session Tracking, II 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 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 PHP4 PHP’s evolution seems to be largely defined by its support for OOP In PHP4, there are no modifiers (public, private, etc) Classes can be defined anywhere 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.<br />\n"; } } function B() { echo "I am a regular function named B in class A.<br />\n"; echo "I am not a constructor in A.<br />\n"; } class B extends A { function C() { echo "I am a regular function.<br />\n"; } } // This will call B() as a constructor. $b = new B; //no () required ?> 28 Constructor oddities What will be printed from the previous block of code? The answer: it depends. In PHP3: ‘A constructor is a function of the same name as the class.’ In PHP4: ‘A constructor is a function of the same name as the class it is being defined in.’ PHP5 has an entirely different way of handling constructors Note: neither PHP3 nor PHP4 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 Fields can be declared at the top of a class definition using the var keyword (i.e. var $internalArray; ) Fields defined with var can only be initialized to constants To access an object field or method: $myObj->myMethod(42); $myObj->myVar = 5; CAUTION: DO NOT DO NOT DO NOT say $myObj->$myVar unless you know what you are doing!!! You can also use the scope resolution operator (::) to access methods/fields “statically” MathStuff::stdDev($array_o_nums); 30 A few other keywords The $this variable (just like in Java) The parent keyword (should only be used when defining a class’ methods) 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() 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 PHP5 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 PHP supports nearly any type of database on the market Most common database used with PHP is MySQL Interactions with databases are what make PHP such a powerful language 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 MySQL mysql_connect($dbhost, $dbuser, $dbpass […]) mysql_query($query [, $linkid]) 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) Returns an associative array with keys being field names $result is a result id resource 34 Conclusion PHP is a very extensive language, with support for a huge number of APIs for databases, XML, images, etc. The old XML parser in PHP4 is a SAX-like parser PHP5 introduces SimpleXML 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 But beware: it also allows for bad coding habits to develop! 35 The End 36