Document Sample
Perl Powered By Docstoc
              Guest Lecture by Ari Gilder

Parts of this lecture adapted from the PHP Manual at

        What is PHP?

   PHP stands for PHP: Hypertext Preprocessor
   PHP is a scripting language
       Often used server side
       There are extensions that allow client side as well
   Especially suitable for web development
       Can be embedded into HTML, like JSP
   Developed by Zend Technologies
       Most current versions are: 5.0.2, 4.3.9

        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…

   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

        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

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

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

   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

        Variables and Types
   PHP variables are usually scalars, like $myVar
   There are four scalar types:
       boolean
       integer
       string
       float
   Two compound types:
       array
       object
   Two special types:
       resource
       NULL

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

        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

   PHP has more or less the same set of operators as C or
   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!!!

        Control Structures
   Same control structures as Java, plus a few more
       declare(directive) statement
            Used for setting execution directives for a block of code (i.e. ticks)
       foreach($arr as $key=>$val)
            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

   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;

       Functions, II
   PHP supports two types of conditional functions:
$makefoo=true;              function foo()
//no foo() here, yet
                              function bar()
if ($makefoo) {               {
  function foo()               echo "I don't exist until foo()
  {                                is called.\n";
   echo “foo() function       }
       only accessible      }
       once program         //bar() doesn’t exist yet
       execution reaches    foo();
       here.\n";            //now bar() exists
  }                         bar();
   Arrays declared using the array() function
       Example: $arr = array(“apples”, “bananas”);
   You can assign keys to a value
       $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

        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

        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

        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

        Some useful String functions
   implode($glue, $arr)
       Fuses the elements of $arr with $glue as a separator
   explode($sep, $str)
       Opposite of implode – splits a string into an array
   nl2br($str)
       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

        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?

    Sample HTML Form – login.html
   <form method=“POST” action=“login.php”>
     User name:
     <input type=“text” name=“user” />
     <br />
     <input type=“password” name=“pass” />
     <br /> <input type=“submit” />

     Processing script – login.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.”);

   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

        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

        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

        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

           Some Object Syntax
   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
        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
       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

        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);

        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

       Some additional features in PHP5
   Different syntax for constructors (but backwards-
    compatible) – 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!!!

        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
   I won’t go into much detail…

        A Taste of MySQL
   mysql_connect($dbhost, $dbuser, $dbpass […])
       Returns a link id resource
       $dbhost is most often “localhost”
   mysql_query($query [, $linkid])
       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

   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!

The End


Shared By: