User Tools

Site Tools


eg-259:lecture16

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
eg-259:lecture16 [2008/11/24 08:28] eechriseg-259:lecture16 [2013/03/06 19:22] – [Introduction to PHP (Part 1)] eechris
Line 1: Line 1:
 +~~SLIDESHOW~~
 +====== Introduction to PHP (Part 1) ======
  
 +**Contact Hour 21**: To be discussed on Tuesday 19th March, 2013.
 +
 +**Lecturer**: [[C.P.Jobling@Swansea.ac.uk|Dr Chris P. Jobling]].
 +
 +An introduction to PHP, one of the most popular server-side scripting languages for web applications.
 +
 +
 +
 +
 +
 +===== Introduction to PHP (Part 1) =====
 +
 +PHP is rapidly becoming the favourite language for server-side web applications development. In this lecture we introduce the language and some of its features. To set PHP in context, you should study this lecture in conjunction with the [[eg-259:lecture5|Introduction to JavaScript]].
 +
 +-----
 +
 +Based on Chapter 12 of Robert W. Sebasta, //Programming the World-Wide Web//, 3rd Edition, Addison Wesley, 2006. and Chapter 12 of Chris Bates, //Web Programming: Building Internet Applications//, 3rd Edition, John Wiley, 2006.
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +===== Contents of this Lecture =====
 +
 +//Introduction to PHP with examples//
 +
 +    * [[eg-259:lecture16#origins_and_uses_of_php|Origins and Uses of PHP]]
 +    * [[eg-259:lecture16#overview_of_php|Overview of PHP]]
 +    * [[eg-259:lecture16#general_syntactic_characteristics|General Syntactic Characteristics]]
 +    * [[eg-259:lecture16#primitives_operations_and_expressions|Primitives, Operations, and Expressions]]
 +    * [[eg-259:lecture16#output|Output]]
 +    * [[eg-259:lecture16#control_statements|Control Statements]]
 +
 +The [[eg-259:examples:php1#examples_from_lecture_16|Examples for PHP Part 1]].
 +
 +
 +===== Learning Outcomes =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - How does a web server determine whether a requested document includes PHP code 
 +  - What are the two modes of the PHP processor? 
 +  - What are the syntax and semantics of the include construct? 
 +  - Which parts of PHP are case sensitive and which are not? 
 +  - What are the four scalar types of PHP? 
 +
 +
 +===== Learning Outcomes (continued) =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - How can a variable be tested to determine whether it is bound 
 +  - How can you specify to the PHP processor that you want uses of unbound variables to be reported 
 +  - How many bytes are used to store a character in PHP? 
 +  - What are the differences between single- and double-quoted literal strings 
 +
 +
 +
 +
 +===== Learning Outcomes (continued) =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - If an integer expression appears in Boolean context, how is its Boolean value determined? 
 +  - What happens when an integer arithmetic operation results in a value that cannot be represented as an integer? 
 +  - If a variable stores a string, how can the character at a specific position in that string be referenced? 
 +  - What does the ''chop'' function do? 
 +  - What is a //coercion//? 
 +
 +
 +===== Learning Outcomes (continued) =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - What are the three ways the value of a variable can be explicitly coerced to a specific type 
 +  - How can the type of a variable be determined? 
 +  - If a string is compared with a number, what happens? 
 +  - What is the advantage of using the unique closing reserved words such as ''endwhile''? 
 +
 +
 +
 +===== Origins and Uses of PHP =====
 +
 +  * Developed by Rasmus Lerdorf in 1994 to allow him to track visitors to his Web site 
 +  * PHP is an acronym for //Personal Home Page//, or //PHP: Hypertext Preprocessor// 
 +  * PHP is an open-source product 
 +  * PHP is used for form handling, file processing, and database access 
 +
 +===== Overview of PHP =====
 +
 +  * PHP is a server-side scripting language whose scripts are embedded in HTML documents 
 +  * PHP is an alternative to CGI, ASP.NET, JSP, and Allaire's ColdFusion 
 +  * The PHP processor has two modes: copy (HTML) and interpret (PHP) 
 +  * PHP syntax is similar to that of JavaScript 
 +  * PHP is dynamically typed 
 +  * PHP is purely interpreted 
 +
 +
 +===== General Syntactic Characteristics =====
 +
 +  * PHP code can be specified in an HTML document internally or externally:
 +    * Internally: ''<?php … ?>'' 
 +    * Externally: ''include ("myScript.inc")'' 
 +  * The file can contain both PHP and HTML 
 +  * If the file contains PHP, the PHP must be enclosed in tags ''<?php … ?>'', even if the include statement is already in ''<?php … ?>'' 
 +  * Every variable name begins with a ''$'' 
 +
 +
 +
 +
 +===== General Syntactic Characteristics (continued) =====
 +
 +  * Three different kinds of comments (Java and Perl):
 +<code php>
 +    // JavaScript-like inline comment
 +    # perl-like inline comment
 +    /* Java-like block comment */
 +</code>
 +  * Compound statements are formed with braces
 +  * Compound statements are not blocks
 +
 +----
 +
 +//explanation//: a block is defined as code for which variables defined between braces (not function bodies), are local to the enclosing block. 
 +Java has this property but JavaScript and PHP do not. 
 +
 +===== Primitives, Operations, and Expressions =====
 +
 +  * [[eg-259:lecture16#variables|Variables]] 
 +  * [[eg-259:lecture16#primitive_types|Primitive Types]]
 +  * [[eg-259:lecture16#strings|Strings]]
 +  * [[eg-259:lecture16#booleans|Booleans]]
 +  * [[eg-259:lecture16#arithmetic_operators_and_expressions|Arithmetic Operators and Expressions]]
 +  * [[eg-259:lecture16#string_operations_and_functions|String Operations and Functions]]
 +  * [[eg-259:lecture16#scalar_type_conversions|Scalar Type Conversions]] 
 +
 +
 +===== Variables =====
 +
 +  * There are no type declarations 
 +  * An unassigned (unbound) variable has the value ''NULL''
 +    * The ''unset'' function sets a variable to ''NULL'' 
 +    * The ''IsSet'' function is used to determine whether a variable is ''NULL'' 
 +  * ''error_reporting(15);'' -- prevents PHP from using unbound variables 
 +  * PHP has many predefined variables, including the environment variables of the host operating system 
 +  * You can get a list of the predefined variables by calling ''phpinfo()'' in a script 
 +
 +===== Primitive Types =====
 +
 +  * //There are eight primitive types//:
 +    * Four scalar types: ''boolean'', ''integer'', ''double'', and ''string'' 
 +    * Two compound types: ''array'' and ''object'' 
 +    * Two special types: ''resource'' and ''NULL'' 
 +  * //Integer// and //double// are like those of other languages 
 +
 +
 +
 +===== Strings =====
 +
 +  * Characters are single bytes
 +  * String literals are single or double quoted
 +  * //Single-quoted string literals//
 +    * Embedded variables are **not** interpolated 
 +    * Embedded escape sequences are **not** recognized 
 +  * //Double-quoted string literals//
 +    * Embedded variables **are** interpolated 
 +    * If there is a variable name in a double-quoted string but you don't want it interpolated, it must be escaped. 
 +    * Embedded escape sequences **are** recognized 
 +  * For both single- and double-quoted literal strings, embedded delimiters must be escaped
 +
 +-----
 +
 +<note>
 +**Characters are single bytes**: This means that, unlike HTML, PHP does not natively support Unicode characters. There are a pair of functions ''utf8_encode()'' and ''utf8_decode()'' which provide some Unicode support. There are implications of this if you want to develop PHP applications accessible in countries which do not use the //utf-8// character set.
 +</note>
 +
 +===== Booleans =====
 +
 +  * values are ''true'' and ''false'' (case insensitive) 
 +  * ''0'' and ''""'' and ''"0"'' are ''false''; other values are ''true'' 
 +
 +
 +===== Arithmetic Operators and Expressions =====
 +
 +  * Usual C-based language operators 
 +  * If the result of integer division is not an integer, a double is returned 
 +  * Any integer operation that results in overflow produces a double 
 +  * The modulus operator coerces its operands to integer, if necessary 
 +  * When a double is rounded to an integer, the rounding is always towards zero 
 +  * //Arithmetic functions//
 +    * ''floor'', ''ceil'', ''round'', ''abs'', ''min'', ''max'', ''rand'', etc. 
 +
 +===== String Operations and Functions =====
 +
 +  * The only operator is period ''.'', for concatenation 
 +  * //Indexing// – ''$str[3]'' is the fourth character 
 +  * //Functions//:
 +    * ''strlen'', ''strcmp'', ''strpos'', ''substr'', as in C 
 +    * ''chop'' -- remove whitespace from the right end 
 +    * ''trim'' -- remove whitespace from both ends 
 +    * ''ltrim'' -- remove whitespace from the left end 
 +    * ''strtolower'', ''strtoupper'' -- convert case of string 
 +
 +
 +
 +===== Scalar Type Conversions =====
 +
 +  * //String to numeric//
 +    * If the string contains a period, an ''e'' or an ''E'', it is converted to double; otherwise to integer 
 +    * If the string does not begin with a sign or a digit, zero is used 
 +  * Explicit conversions – //casts//
 +    * e.g., ''(int)$total'' or ''intval($total)'' or ''settype($total, "integer")''
 +  * The type of a variable can be determined with ''gettype'' or ''is_type'':
 +<code php>
 +      gettype($total)  // may return "unknown"
 +      is_integer($total) // a predicate function
 +</code>
 +
 +
 +===== Output =====
 +
 +  * Output from a PHP script is HTML that is sent to the browser
 +  * HTML is sent to the browser through standard output
 +  * There are three ways to produce output: ''echo'', ''print'', and ''printf''
 +    * ''echo'' and ''print'' take a string, but will coerce other values to strings:
 +<code php>
 +       echo "whatever";   # Only one parameter
 +       echo("first <br />", $sum)  # More than one
 +       print "Welcome to my site!";  # Only one
 +</code>
 +
 +===== More Output =====
 +
 +  * ''echo'' has a shorthand ''<?= ?>'' that makes it pleasanter to print the value of a PHP variable in //copy mode//:
 +<code html>
 +<p>Hello <?=$name?>, welcome to my site. It's <?=date("D M j Y")?> today.</p>
 +</code>
 +----
 +  * This shorthand should only be used for printing variables or with functions that return a string.
 +  * The short syntax only works with the [[http://uk2.php.net/manual/en/ini.core.php#ini.short-open-tag|short_open_tag]] configuration setting enabled (which it is in Ubuntu). 
 +
 +===== Hello World (PHP) =====
 +
 +  * PHP code is placed in the body of an HTML document
 +<code html>
 +<!DOCTYPE html>
 +<html lang="en">
 +  <head>
 +    <meta charset="utf-8" />
 +    <title> Trivial php example </title>
 +  </head>
 +  <body>
 +    <?php
 +      print "Welcome to my Web site!";
 +    ?>
 +  </body>
 +</html> 
 +</code>
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +===== First PHP Example =====
 +
 +A simple example to illustrate a PHP document: [[/eg-259/examples/lecture16/today.php|today.php]] ([[http://localhost/eg-259/examples/lecture16/today.php|today.php @ localhost]])
 +
 +----
 +
 +<code php>
 +<!DOCTYPE html>
 +
 +<!-- today.php - A simple example to illustrate a PHP document -->
 +<html lang="en">
 +  <head> 
 +    <meta charset="utf-8" />
 +    <title> today.php &ndash; A simple example to illustrate a PHP document  </title>
 +  </head>
 +  <body>
 +    <p>
 +      <?php
 +        print "<b>Welcome to my home page <br /> <br />";
 +        print "Today is:</b> ";
 +        print date("l, F jS");
 +        print "<br />";
 +      ?>
 +    </p>
 +  </body>
 +</html>
 +</code>
 +
 +Result:
 +
 +{{eg-259:l16-today.png|Result of executing PHP script today.php}}
 +
 + 
 +
 +===== Control Expressions =====
 +
 +  * Relational operators -- same as JavaScript, (including ''==='' and ''!==''
 +  * Boolean operators -- two sets, ''&&'' and ''and'', ''||'' and ''or''
 +
 +===== Selection statements =====
 +
 +  * ''if'', ''if-else'', ''elseif'' 
 +  * ''switch'' -- as in C 
 +  * The ''switch'' expression type must be integer, double, or string 
 +
 +===== Looping constructs =====
 +
 +  * ''while'' -- just like C 
 +  * ''do-while'' -- just like C 
 +  * ''for'' -- just like C 
 +  * ''foreach'' -- discussed later 
 +
 +===== Other statements =====
 +
 +  * ''break'' -- in any ''for'', ''foreach'', ''while'', ''do-while'', or ''switch'' 
 +  * ''continue'' -- in any loop 
 +
 +
 +===== Alternative componund delimiters =====
 +
 +  * "syntax sugar" -- improves readability:
 +<code php>
 +    if (...) :
 +      ...
 +    endif;
 +</code>
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +===== Another Example =====
 +
 +An example to illustrate loops and arithmetic: [[/eg-259/examples/lecture16/powers.php|powers.php]] ([[http://localhost/eg-259/examples/lecture16/powers.php|powers.php @ localhost)]]
 +
 +----
 +
 +  * Code:
 +<code php>
 +<!DOCTYPE html>
 +
 +<!-- powers.php
 +     An example to illustrate loops and arithmetic
 +     -->
 +<html lang="en">
 +  <head> 
 +    <meta charset="utf-8">
 +    <title> powers.php &ndash An example to illustrate loops and arithmetic </title>
 +  </head>
 +  <body>
 +    <table border = "border">
 +      <caption> Powers table </caption>
 +      <tr>
 +        <th> Number </th>
 +        <th> Square Root </th>
 +        <th> Square </th>
 +        <th> Cube </th>
 +        <th> Quad </th>
 +      </tr>
 +      <?php
 +        for ($number = 10; $number <=20; $number++) {
 +          $root = sqrt($number);
 +          $square = pow($number, 2);
 +          $cube = pow($number, 3);
 +          $quad = pow($number, 4);
 +          print("<tr align = 'center'> <td> $number </td>");
 +          print("<td> $root </td> <td> $square </td>");
 +          print("<td> $cube </td> <td> $quad </td> </tr>");
 +        }
 +      ?>
 +    </table>
 +  </body>
 +</html>
 +
 +</code>
 +
 +  * Result
 +
 +{{eg-259:l16-powers.png|Result of executing the powers.php script}}
 + 
 +
 +
 +
 +
 +===== Intermingling HTML and PHP =====
 +
 +  * HTML can be intermingled with PHP script
 +<code php>
 +    <?php
 +      $a = 7;
 +      $b = 7;
 +      if ($a == $b) {
 +        $a = 3 * $a;
 +    ?>
 +    <br />
 +    At this point, $a and $b are
 +    equal <br />
 +    So, we change $a to three times $a
 +    <?php
 +      }
 +    ?> 
 +</code>
 +
 +----
 +
 +<note warning>
 +this is not necessarily a good idea! Notice how the end brace for the conditional is separated from the loop body by several unrelated HTML tags. This produces fragile code -- if the second set of PHP tags where removed, a syntax error would occur which might be difficult to track down.
 +</note>
 +
 +
 +
 +===== Summary of This Lecture =====
 +
 +//Introduction to PHP with examples//
 +
 +    * [[eg-259:lecture16#origins_and_uses_of_php|Origins and Uses of PHP]]
 +    * [[eg-259:lecture16#overview_of_php|Overview of PHP]]
 +    * [[eg-259:lecture16#general_syntactic_characteristics|General Syntactic Characteristics]]
 +    * [[eg-259:lecture16#primitives_operations_and_expressions|Primitives, Operations, and Expressions]]
 +    * [[eg-259:lecture16#output|Output]]
 +    * [[eg-259:lecture16#control_statements|Control Statements]]
 +
 +The [[eg-259:examples:php1#examples_from_lecture_16|Examples for PHP Part 1]].
 +
 +===== Learning Outcomes =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - How Does a Web server determine whether a requested document includes PHP code 
 +  - What are the two modes of the PHP processor? 
 +  - What are the syntax and semantics of the include construct? 
 +  - Which parts of PHP are case sensitive and which are not? 
 +  - What are the four scalar types of PHP? 
 +
 +
 +===== Learning Outcomes (continued) =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - How can a variable be tested to determine whether it is bound 
 +  - How can you specify to the PHP processor that you want uses of unbound variables to be reported 
 +  - How many bytes are used to store a character in PHP? 
 +  - What are the differences between single- and double-quoted literal strings 
 +
 +
 +
 +
 +===== Learning Outcomes (continued) =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - If an integer expression appears in Boolean context, how is its Boolean value determined? 
 +  - What happens when an integer arithmetic operation results in a value that cannot be represented as an integer? 
 +  - If a variable stores a string, how can the character at a specific position in that string be referenced? 
 +  - What does the ''chop'' function do? 
 +  - What is a //coercion//? 
 +
 +
 +===== Learning Outcomes (continued) =====
 +
 +//At the end of this lecture you should be able to answer these questions//:
 +
 +  - What are the three ways the value of a variable can be explicitly coerced to a specific type 
 +  - How can the type of a variable be determined? 
 +  - If a string is compared with a number, what happens? 
 +  - What is the advantage of using the unique closing reserved words such as ''endwhile''? 
 +
 +
 +
 +
 +
 +
 +
 +
 +
 +===== What's Next? =====
 +
 +** Introduction to PHP (Part 2) **
 +
 +//Further features of the PHP language//
 +
 +  * [[eg-259:lecture17#arrays|Arrays]] 
 +  * [[eg-259:lecture17#functions|Functions]]
 +  * [[eg-259:lecture17#pattern_matching|Pattern Matching]]
 +
 +[[eg-259:lecture15|Previous Lecture]] | [[eg-259:home]] | [[eg-259:lecture17|Next Lecture]]
eg-259/lecture16.txt · Last modified: 2013/03/08 18:03 by eechris