Workshop in Computational Bioskills - Lesson 9

Workshop in Computational Bioskills - Spring 2008

Lesson 9 - Building a Dynamic web site 

Building a website is done in HTML : For a short introduction to HTML click here

Building a dynamic website requires a bit more...

PHP Basics Introduction Variables Arrays Control Flow


PHP - Dynamic Web Pages Language

PHP: Hypertext Preprocessor programing language, used for writing
dynamic web pages, when the page content depends on the input given by the user.

Several facts on PHP


Why PHP?

Getting Started

File Hello_world.php: 

<html>
<head>
    <title> PHP Hello </title>
</head>
<body>
  <b>
    <? print "Hello World!" ?>
  </b>
</body>
</html>

But that was not really dynamic (why?).
Let's see for example how to create a simple_form.php
(recall how to write forms).
We will revisit this example later on. First let's continue with the basics...


Scalar Variables PHP has two data types: strings and numbers.

o Like the perl scalars (denoted by the "$" sign).
o Naming convention - letters, underscore and numbers
  (not in the beginning).
o Arithmetic operations permitted: just like in perl.

Numbers 
Not much to say here - just like in perl and other languages.
Boolean
false is represented by the empty string, empty array and the number zero.
Strings

Strings appear in three formats: 
Single quotes: <? print 'That\'s your name: $name' ?> // That's your name: $name
Double quotes: <? print "Your name is $name" ?> // Your name is Dani
Strings with more than one line are done with Here-document (Heredoc) 
syntax:

 <? print  
<<< HTMLBLOCK
<html> 
  <body> 
    some text...
  </body> 
</html>     
HTMLBLOCK;
?>  

Prints all the text between the HTMLBLOCK tags
o Variables inside strings: $preparation = '
Braise'; $meat = 'Beef'; print "{$preparation}d $meat with Vegetables"; // Braised Beef with Vegetables Variable Comparison
  • Use '==' to compare variables
  • strings are compared lexicographically
  • strings that contain numbers are sometimes compared as strings and sometimes as numbers, depends on the compared variable
  • strcmp() - always compare as strings, therefore ("54213" < "56") returns false, but strcmp("54213","56") return -1, i.e. 56 is greater than 54213.
  • There are many useful functions on Strings:
    • trim( $string ) removes whitespace from the beginning and end of a string.
    • strlen( $str ) returns the length of the string.
    • printf( format, $str ) formated print, like in C and Perl.
    • strcasecmp( $str1, $str2 ) compares the strings, case insensitive.
    • strtolower( $str ) and strtoupper( $str ) - change the string to be all lower case or upper case.
    • ucwords( $str ) upper case the first letter of each word in the string
    • substr($str, offset, length) extract length number of chars from the string, starting in offset. If offset is negative, it is defined from the end.
    • str_replace( $substr, $rep, $string ) replace each appearance of $substr with $rep
    Let's see a simple example for manipulating text.

    Arrays
    
    o The definition of Arrays in PHP includes both lists (associative
      arrays) and hashes, where the list is a specific case of an hash.
    o The name of the hash/list is a regular variable name - beware
      not to override existing variables. 
    o The array keys must be scalar (string or number), and the
      array elements can be either scalars or arrays.
    o An array is created by the array() construct.
    
    Associative Array (Hash) Declaration:
    
    By calling the constructor: 
    
    $vegetables = array( 'corn' => 'yellow', 
                        'carrot' => 'orange',
                        'tomato' => 'red' );
    
    The keys can be numbers, string or both. 
    
    Or by a direct assignment: 
    
    $vegetables['corn'] = 'yellow';
    $vegetables['carrot'] = 'orange';
    $vegetables['tomato'] = 'red';
    
    $dinner[0] = 'chicken';
    $dinner[1] = 'rice';
    
    $price['perl book'] = 29.99;
    $price['php book'] = 25.0;
    
    
    List Declaration:
    
    When the keys are ordered integers, the hash is very much like an
    ordered list. PHP has a shortcut to generate a list: 
    
    
    $dinner = array('chicken', 'rice');
    print "$dinner[1]"; // rice
    
    
    
    In fact...
    
    // This array ...
    array(1 => "Peter", "paul", "Mary", "Peter"=>"Jan");
    
      // ...is the same as this array
    array(1 => "Peter", 2 => "paul", 3 => "Mary", "Peter"=>"Jan");
    
    
    


    Array Operations
    
    o An array element can be manipulated like a regular variable: 
    
    
    $dinner[1] = 'potato'; // assignment
    
    $cost = $price['perl book'] + $price['php book']; //arithmetic operations
    
    unset( $price['perl book'] ); // removes the element from the array.
                                  // It is different from 
    			      // setting the value to zero or to empty string 
    
    
    o $arr[] - add a new element to the end of array: 
    
             $dinner[] = 'ice-cream'; // $dinner[2] is now 'ice-cream'.
    
    
    o count( $arr ) - return the number of elements in the array.
    
    
    o foreach($arr as $key=>$value) - iterate over the hash
    elements: 
    
    foreach ($vegetables as $veg=>$color)
    {
    // the values are copied to $veg and $color
     // therefore changing their values does not affect the list.
     print "<tr><td>$veg</td><td>$color</td></tr>\n";
    }
    
    
    o foreach($arr as $value) - shortcut for lists:  
    
    foreach ($dinner as $dish)
    {
     print "going to eat $dish\n";
    }
    
    
    Note: The element are accessed in the order they were added to the 
    array. if you want to access them with index order, use a standard for() loop. 
    
    o Finding an element in the array: 
    
    // array_key_exists looks for the given key in the array and 
    // returns true or false; 
    
    if (array_key_exists('corn',$vegetables))
    { 
     print "yes, we have corn\n"; 
    }
    
    
    // in_array looks for the given value in the array and 
    // returns true or false. The search is case sensitive:
    
    if (in_array('red',$vegetables)
    {
     print "yes, we found something red in the vegs list\n"; 
    }
    
    
    // array_search looks for the given value in the array and 
    // returns its key.
    
    $key = array_search('red',$vegetables);
    if ($key)
    {
     print "the red vegetable is: $key\n";
    }
    
    
    o implode($delim, $arr) -
    print of the value list (like perl join).
    
    print "<tr><td>".implode("</td><td>",$dinner)."</td></tr>";
    
    o explode($delim,$string) - split string into an array.
    
    $colors = 'red, white, blue, green';
    
    $color_list = explode(', ',$colors);
    
    


    Array Sorting

    Lexicographic ordering of the array elements:


    Multidimensional Arrays
    The value of an element can be itself an array. 
    
    // Declaration
    
    $prices =  array(
               'red' => array('apple'=> 7.00, 'tomato'=> 4.30 ),
    	   'green' => array('letus' => 2.00,'cucumber' => 3.5),
    	   'yellow' => array('corn' => 10.00 ,'lemon' => 5.05 ) );
    
    // Now let's print it:
    
    print $prices['red']['tomato']; // 4.30
    print $prices['green']['cucumber']; // 3.5
    
    
    

    Control Flow
    Similar to c and perl: if, elseif, else, switch, while, do...while, for, foreach


    Making Web Forms
    Web forms are essential in almost any dynamic web application. We saw how to write a
    form in HTML, and here we'll see how to process the user input.

    
    Let's start with an example we already saw:
    
    simple_form.html:
    
    <html>
     <head>
      <title>PHP Test</title>
     </head>
     <body>
      <form action="action.php" method="get">
       <p>Your name: <input type="text" name="my_name"> </p>
       <p>Your age:  <input type="text" name="my_age"> </p>
       <p><input type="submit" ></p>
      </form>
     </body>
    </html>
    
    
    The user fills the 2 windows, and the script action.php is 
    called. The result is displayed on the browser: 
    
    <html>
     <head>
      <title>PHP Action</title>
     </head>
     <body>
      Hi <?php echo $_GET['my_name']; ?>.
      You are <?php echo $_GET['my_age']; ?> years old.
     </body>
    </html>
    
    
    Can we do it in a single php file? simple_form.php: <html> <head> <title>PHP Form</title> </head> <body> <?php if array_key_exists('my_name',$_GET) { print "Hi ".$_GET['my_name']; print "You are ".$_GET['my_age']." years old."; } else { print<<< _HTML_ <form method="get" action="$_SERVER[PHP_SELF]"> <p>Your name: <input type="text" name="my_name" /></p> <p>Your age: <input type="text" name="my_age" /></p> <p><input type="submit" /></p> </form> _HTML_; } ?> </body> </html>
    • $_POST Hash holding the variables that were send using "POST" method
    • array_key_exists($_POST['var']) True whenever the form is submitted - also when the var value is empty.
    • $_SERVER Holds various information about the server and the php request.
      • PHP_SELF Holds the path to the current URL (/~bioskill/Lesson9/simple_form.php)
      • SERVER_NAME The server name (www.cs.huji.ac.il)
      • DOCUMENT_ROOT The path in the server file system (/cs/course/current/bioskill/www/Lesson9/)
      • REMOTE_ADDR IP address of the user
      • HTTP_USER_AGENT User agent ID

    Input Validation
    • Display error message (or the original form) upon empty input
    • Running your program with bad parameters may cause crashes
    • Preventing cross-site scripting attack - a user can insert JavaScript in the text area...
    
    if ( $_GET['_submit_check'] == 1 ) 
    { 
        $form_errors = validate_form();
        if ($form_errors != '') {
            show_form($form_errors);
        } else {
            process_form();
        }
    }
    else {
        show_form();
    }
    
    
    • _submit_check is hidden variable - it is not seen on the browser.
    • The functions can be implemented in any way.
    • To check numeric values, use intval(), floatval() that extract the number from the string,
      and strval() that return the number as a string.
    A simple check:
    
    
    function validate_form() 
    {
    $error = '';
    if (strlen( trim($_POST['product'])) < 1 ) 
      {
        $error = 'Please enter a product name';
      }
    
    if ($_POST['price'] != strval(floatval($_POST['price'])))
      {
        $error = 'Please enter a valid price.';
      }
    return $error;
    }
    
    
    Run valid_price.php
    
    

    <select> Menus
    
    o Displays a list of options (option to select one item or several items)
    
    
    <form method="get" action="order.php">
    <select name="order">
    <option>Book</option>
    <option>Ball</option>
    <option>Car</option>
    </select>
    </form>
    
    
    o To validate it, just check that the given value is one of the options. o Run valid_list.php o valid_multiple_list.php enables the choice of multiple items.
    Displaying default parameters
    o With HTML we can display a default parameters in the form example. o PHP you can just print these default options to the HTML file.