Intro to PHP

OBJECTIVES

In this unit, the student will learn:
  • how to create a simple PHP web page
  • how to set up a private web server for off-line debugging
  • basic PHP syntax

Client-server model of the Web

  • Client sends request for URL
  • Server sends back HTML code
  • Client browser renders HTML for user
client-server model

Scripting models

Scripting adds dynamic content, in response to user interaction or other cues.
  • Client-side scripting
    • Executes on client browser (e.g.JavaScript)
    • Browser must be script-aware
    • Code can be viewed by user
  • Server-side scripting
    • Executes on server (e.g.PHP)
    • Scripting is transparent to client: content received is normal HTML
    • Code is hidden from user
PHP is a server-side scripting system.

Server-side scripting

diagram of server side scripting
(Figure adapted from Stepp et al.Fig.5.1.)
Usually database access on server side is involved.

HTTP GET request

Format of an HTTP GET request:
GET file-path HTTP/version
other header lines
(blank line)

Try it: from a command-line, type the following exactly
telnet www.dsm.fordham.edu 80
GET /~janeuser/ HTTP/1.0
(blank line)
(Version now normally 1.1, requires other headers.)

See RFC 2616 for original HTTP 1.1 protocol definition.

HTTP Response

Form of response:

HTTP/version status
Content-Length: bytes
Content-Type: type/subtype
other headers
    (blank line)
content body

Example response from GET /~janeuser/ HTTP/1.0
  • View headers in Firefox Developer Toolkit, Network tab.

HTML headers in PHP

  • Most headers are supplied automatically by the web server
  • Custom headers can be provided using PHP header() function
    • Must be called before any content is output
  • Special case:
    • setting a cookie has its own specific function: setcookie()

Embedded PHP

General form of a PHP page:

HTML content
<?php
PHP statements
?>
HTML content
  • PHP blocks may be interspersed with HTML code
  • PHP code will be interpreted and replaced with HTML
  • Client sees only the interpreted result

W3C Validation

  • Validation by file upload will not work.
    • Validator will see PHP code as invalid HTML.
    • (Actually will not see it at all: uploaded file is wrong type, .php not .html.)
  • Validation by visiting Web URL will work, if PHP output is valid.
    • Validator will see only the HTML after PHP is interpreted.

Debugging and demo

When developing PHP pages:
  • Visiting PHP file locally (file:// URL) on your computer will not work.
    • Browser does not interpret PHP.
  • Three options:
    • Work in CIS Dept. lab where you can directly edit file in your public_html directory.
    • Upload document to web server each time you want to test it.
    • Install a private web server on your own computer.

Setting up a private web server

Linux gurus: simply install needed packages using package manager, or command line:
  • Fedora: yum install httpd mariadb phpMyAdmin
  • Debian: apt-get install apache2 mysql-client mysql-server phpmyadmin
(Requires you to be root or use sudo.)

For others, I recommend XAMPP package.

Running your own web server

Important: visit files through server with http URL, not as file URL.
  • Put your PHP files into the server's web space:
    • XAMPP: C:\xampp\htdocs
    • WAMP: C:\wamp\www
    • For other systems, use phpinfo to find where DOCUMENT_ROOT is
  • URL of files will have localhost as address portion.

The phpinfo() function

Complete PHP document:

<?php
phpinfo();
?>
  • Generates all tags for complete page
  • Lists information about server, PHP configuration
  • Shows values of useful global variables
Result   Example not live for security reasons. Shows default XAMPP installation.

Getting help

  • Lots of resources are available at http://www.php.net
    • tutorials
    • reference manual
    • user contributed notes
  • For help on a specific function, Google it
    • E.g. Google: php htmlspecialchars

Debugging

What if your code has a syntax error?
  • Server may be configured to dump error messages into web page.
    • XAMPP and WAMP default configuration does so. (Another reason to set up your private server.)
    • Try it now:
      • In Notepad++, add a line bogus = 0; to hello.php at line 10
      • Save, visit, see error message:
Parse error: syntax error, unexpected '=' in C:\xampp\htdocs\hello.php on line 10
(The actual error is a missing $ on $bogus.)

Debugging on dsm

If you are developing in your erdos account, or other linux system:
  • Server usually not configured to dump error messages into web page.
    • This is the case for www.dsm.fordham.edu
  • If PHP has errors, you will see a blank page.
    • Need to check the server error log, usually
      /var/log/httpd/error_log.
    • Access normally restricted to root user but
    • we have set up a user-readable directory.
    • Log in to a shell on erdos (e.g. via PuTTY) or a lab machine and use
      tail /usr/local.dsm/etc/httpd/logs/error_log

Superglobal variables

OK, now let's have some fun.
  • Superglobals are pre-set by the PHP system
  • Provide information about
    • server operating system
    • web server version, environment
    • web browser version
    • cookies, etc.
  • Find them by looking at output of phpinfo()
    • get name of variable from list
    • then get values from $_SERVER['variable-name']

Example    PHP Code

Customizing the page

Superglobal variables allow HTML to be customized to the browser.

Example   PHP Code
  • The example uses strpos(haystack,needle) function, which returns position of needle string in haystack string, or FALSE if not found.
  • A real life example would use the test to work around known browser incompatibilities.
(Example uses HTTP_USER_AGENT to detect IE browser. See http://www.useragentstring.com/ for info on User Agent Strings for various browsers.)

Interspersing PHP and HTML

  • Last example uses print function to put different content into page in different branches of if.
  • Also possible to jump in and out of PHP mode within logic branches.
    • This is preferable when you have a lot of HTML to put out in each branch.

Example   PHP Code

Yet another way to include PHP

Example of shorthand way to include PHP:
Your IP address is <?= $_SERVER['REMOTE_ADDR'] ?>
  • The notation <?= expression ?> is shorthand for
    <?php echo expression ?>
  • Only works if server has enabled short_open_tag option
    • see phpinfo() output to see if option is enabled
      • Nowadays it tends to be enabled even if phpinfo() says it isn't

Example   PHP Code   non-short_open_tag version: PHP Code

PHP basics

  • Syntax more Perl-like than C++-like
  • Comments:
    • // single-line comment
    • # single-line comment
    • /* multi-line comment */
  • All variable names start with $
  • Statements end with ; (mandatory except at end of PHP block)
  • Control structures: if, for, while, do...while
    • same form as Perl or JavaScript
    • except it has elseif (one word) that JavaScript does not
    • use braces { } to group multiple controlled statements
Example   PHP Code

Alternative syntax

PHP allows an alternative form for control statements
  • Replace opening brace by colon :
  • Replace closing brace by endkeyword;
    • This can be clearer when embedding PHP in HTML.
E.g.
if( test ):
  statements
endif;

Example   PHP Code

Data types

  • Values in PHP are dynamically typed.
  • Built-in types:
    • int or integer : integer
    • float or double : real number
    • bool or boolean : logical (true/false)
    • string : text string
    • NULL : variable has no value
  • The type can change if value is changed.
  • In mixed expressions, type is converted automatically.
    • Can also cast, e.g. (int)$x

Operators

PHP operators for arithmetic:
  • + : addition
  • - : subtraction
  • * : multiplication
  • / : division
  • % : remainder
  • ++, -- : increment, decrement
Other operators:
  • = : assignment, yields value assigned
  • +=, -=, etc.: operate and assign
  • . (period): string concatenation
Beware: unlike JavaScript, + is only addition. "foo" + "bar" = 0.

Logical operators

Operators for combining boolean values:

&& : AND    || : OR    ! : NOT

  • Boolean literals are FALSE and TRUE
  • Any expression can be converted to boolean:
    • 0, empty string, empty array, NULL, unset variable evaluate to FALSE
    • any other values evaluate to TRUE

Logical tests

Comparison operators:

== equal to   != not equal to
< less than   <= less than or equal
> greater than   >= greater than or equal

These perform data type conversions as needed. The following comparisons do not convert data types:

=== equal to and same type
!== not equal to or different type

Math functions

PHP has many mathematical functions.
  • abs(x) : magnitude of x
  • min(x,y), max(x,y) : smaller, larger of x, y
  • sqrt(x) : √x
  • round(x) : round x to nearest integer
  • round(x,d) : round x to d digits after decimal point
Unlike JavaScript, no Math. prefix.

Example PHP Code

Strings

  • String values may be enclosed in either:
    • single quotes 'This is a string' or
    • double quotes "Another string"
    • As usual, straight quotes only!
  • Difference: variables are expanded inside double quotes but not single quotes.
$x = 'Joe';
$y = "Hello, $x!"; // $y = 'Hello, Joe!'
$z = 'Hello, $x!'; // $z = 'Hello, $x!'

Strings, cont'd

  • Strings may span multiple lines between opening and closing quotes.
$str = "Line 1
Line 2"


Example   PHP Code

(Compare page source with PHP code.)

String functions

There are many built-in functions for working with strings:
  • strlen(string) : length of string
  • trim(string) : remove leading & trailing spaces
  • htmlspecialchars(string) : escape special HTML chars to make safe as content
  • strpos(haystack,needle) : position of needle in haystack
And many more.
Look up usage on php.net by Googling “php” and name of function.
Example   PHP Code

Arrays

Arrays in PHP are very similar to those in JavaScript, more flexible than those in C++.
  • Can contain elements of differing types
  • Can grow or shrink dynamically
  • Can have holes (undefined elements)
  • Can be indexed by integer or keyword string
Declaring an array:
$a = array(); // empty array
$a = array(value1, value2, ...) // initialized array

Accessing an array element, numbering starts at 0:
$a[1] // is value2           Example   PHP Code

Debugging arrays

  • If you write print $a; where $a is an array, result is just the word “Array”.
  • To see contents of array (or other objects):
    print_r(array);
Example   PHP Code

Array functions

PHP has many functions for working with arrays
  • count : number of elements in array
    • Only counts defined elements: skips holes
  • array_push, array_pop : add/remove elements from end of array
  • array_shift, array_unshift : add/remove elements from front of array
Example   PHP Code

The foreach loop

To loop through array elements:
foreach( $array as $element ) {
  statements
}
  • Skips any undefined elements
  • The $element is a copy of the element
    • Loop body cannot change the array contents
Example   PHP Code

Associative arrays

A PHP array can be indexed (keyed) by a string.
Declaring an associative array:
$a = array(key1 => value1, key2 => value2, ...);

Accessing an array element: $a["key2"] // is value2

Looping through elements:
foreach( $array as $key => $value ) {
  statements
}

Example   PHP Code

Functions

A function is a named block of code.
Declaring a function:
function function-name ( $arg1, $arg2, ... ) {
  statements
}
  • Argument can be given default value by listing as $arg=value
  • Function may return a value using return expr

Example   PHP Code

Call by reference

  • By default, function arguments are passed by value.
    • they are copies of the originals
    • may be changed by the function without affecting the originals.
  • For call by reference, precede name by &

Example   PHP Code

Scope of variables

  • In PHP, variables have one of two scopes:
    • Declared outside any function: global scope
      • available throughout file
    • Declared inside a function: local scope
      • available only inside function
      • Note: loop index is not local to loop body.
    • For function to access global variable requires global declaration.

Example   PHP Code

Including files

To insert contents of a file into page, use
include(filename);          Example   PHP Code   functions   header
  • File path is relative to script location
    • Does not refer to URL space.
  • Use for content shared by multiple pages
    • library of functions (DO enclose in PHP tags)
    • blocks of HTML boilerplate (NEED NOT have body tag etc.)
  • Variants:
    • require : same as include but fatal error if file not found
    • include_once and require_once : same as above, but prevent including same file twice
      • best for shared functions