PHP

CSE 190 M (Web Programming) Spring 2007

University of Washington

Reading: Sebesta Ch. 12

Except where otherwise noted, the contents of this presentation are © Copyright 2007 Marty Stepp and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.0 Strict Valid CSS!

What is PHP?

Why PHP?

Why use PHP instead of Javascript?

Similarities between PHP and Javascript

Differences between PHP and Javascript

PHP files

A typical web server request using PHP

PHP server

Hello, World!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello world</title>
<meta http-equiv="Content-Type"
 content="text/html; charset=iso-8859-1" />
</head>
<body>

<?php
print("Hello, World");
?>

</body>
</html>

System information: phpinfo()

<?php
phpinfo();
?>

Variables

$name = value;
$username = 'pinkHeartLuvr78';
$age = 16;
$thisClassRocks = TRUE;
$éléphant = "totally legit variable name";

Injecting text: print()

print("text");
print("Hello, World!");
print("Escape \"chars\" are the SAME as in Java!\n");

print("You can have
line breaks in the string
and they'll show up");

print('A string can use single-quotes.  It\'s cool!');

Interpreted strings

print("This will print the variable's value: $var");
print('This will print the variable\'s name: $var');

Comments

# single-line comment

// another single-line comment style

/*
multi-line comment
*/

Operators

for loop

for (initialization; condition; update) {
    statements;
}

Write a loop that prints out squares from 0 - 81 like this: "0 squared is 0."

for($i = 0; $i < 10; $i++) {
    print("<p> $i squared is " . $i * $i . " </p>");
}

Including scripts: include()

include("filename");
include("header.php");

String type

$favoriteFood = "ethiopian";
$favoriteFood[2];            # evaluates to "h"

String functions

$name = "Kenneth Kuan";
$length = strlen($name);              # 12
$cmp = strcmp($name, "Jeff Prouty");  # > 0
$index = strpos($name, "e");          # 1
$first = substr($name, 8, 4);         # "Kuan"
$upper = strtoupper($name);           # "KENNETH KUAN"
NameJavascript or Java Name
explode, implode split, join
strlen length
strcmp compareTo
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim substring

Numbers

$piApprox = 355/113;          # double: 3.141592920354
(int) $piApprox;              # int: 3
round($piApprox);             # double: 3

Mathematics

Boolean type

$feelsLikeSummer = FALSE;
$phpIsRad = True;
$studentCount = 96;
(bool) $studentCount;     # evaluates to TRUE

NULL

if/else statement

if (condition) {
    statements;
} elseif (condition) {
    statements;
} else {
    statements;
}

while loop

while (condition) {
    statements;
}
do {
    statements;
} while (condition);

Reading directories

$DIR = "awesomeFiles";
$dh = opendir($DIR);
while ($file = readdir($dh)) {
    print("$file<br>\n");
}
closedir($dh);

Practice problem: image gallery

Given a directory called thumbs containing picture thumbnails and a directory called images which contains the full images, create a page that displays the thumbnails. These should link to their corresponding full-sized image. The filenames are the same in the two directories.

gallery screenshot

Functions

function name(parameterName, ..., parameterName) {
    statements;
}
function quadratic($a, $b, $c) {
    return -$b + sqrt($b*$b - 4*$a*$c) / (2*$a);
}

Calling functions

name(parameterValue, ..., parameterValue);
$root = quadratic(1, $x, $a + 3);

Arrays

$name = array(value0, value1, ..., valueN);   # create
$name[] = value;                          # create or append
$name[index] = value;                      # set element value
$name[index]                              # get value
$arr[] = 23;       # creates array with 23 at index 0
$arr2 = array("some", "strings", "in", "an", "array");
$arr2[] = "Ooh!";  # add string to end (at index 5)

foreach loop

foreach (array as $name) {
    ...
}
$stooges = array("Larry", "Moe", "Curly", "Shemp");
foreach ($stooges as $stooge) {
    print("<p>Moe slaps $stooge</p>");  # even himself!
}

Array functions

Array function example

$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
    $tas[$i] = strtolower($tas[$i]);
}                                 # ("md", "bh", "kk", "hm", "jp")
$morgan = array_shift($tas);      # ("bh", "kk", "hm", "jp")
array_pop($tas);                  # ("bh", "kk", "hm")
array_push($tas, "ms");           # ("bh", "kk", "hm", "ms")
array_reverse($tas);              # ("ms", "hm", "kk", "bh")
sort($tas);                       # ("bh", "hm", "kk", "ms")
$best = array_slice($tas, 1, 2);  # ("hm", "kk")

Regular expressions in PHP (PDF)

Regular expression example 1

$str = "the quick    brown  fox";
$words = preg_split("/[ ]+/", $str);
                         # ("the", "quick", "brown", "fox")

for ($i = 0; $i < count($words); $i++) {
    $words[$i] = preg_replace("/[aeiou]/", "*", $words[$i]);
}
                         # ("th*", "q**ck", "br*wn", "f*x")

$str = implode("_", $words);
                         # "th*_q**ck_br*wn_f*x"

Regular expression example 2

$str = "<10><20><30><40>";
if (preg_match("/(<\d\d>){4}/", $str)) {
    $str = preg_replace("/[<>]+/", ",", $str);
    $tokens = preg_split("/0/", $str);
    foreach ($tokens as $num) {
        print("Number: $num\n");
    }
}

Reading files

$text = file_get_contents("filename");
$lines = preg_split("/\n/", $text);
foreach ($lines as $line) {
    do something with $line;
}

Reading files example

# Returns how many lines in this file are empty or just spaces.
function count_blank_lines($file_name) {
    $text = file_get_contents($file_name);
    $lines = preg_split("/\n/", $text);
    $count = 0;
    foreach ($lines as $line) {
        if (strlen(trim($line)) == 0) {
            $count++;
        }
    }
    return $count;
}
...
print(count_blank_lines("15-php.html"));

Query parameters: $_GET and $_POST

$cc = $_GET["creditcard"];        # if it is a GET request
$username = $_POST["username"];   # if it is a POST request

Checking for a parameter's existence

if (array_key_exists("creditcard", $_GET)) {
    $cc = $_GET["creditcard"];
    ...
} else {
    print("Error, you did not submit a credit card number.");
    ...
    return;
}

Building query strings with urlencode

$str = "Marty's cool!?";
$str2 = urlencode($str);   # "Marty%27s+cool%3F%21"
$url = "http://example.com/thing.php?param=$str2";
$str3 = urldecode($str2);  # "Marty's cool?!"

Headers

Practice problem: Baby Names server

Write a PHP script that mimics the Baby Names server app used in Homework 5. Have your script accept a query parameter named type that is either set to list, meaning, or rank.

Non-consecutive arrays

$autobots = array("Optimus", "Bumblebee", "Grimlock");
$autobots[100] = "Hotrod";

Associative arrays

$blackbook["marty"] = "206-685-2181";
$blackbook["stuart"] = "206-685-9138";
...
print("Marty's number is " .
      $blackbook["marty"] . ".\n");
print("Marty's number is {$blackbook['marty']}.\n");

Creating an associative array

$name = array(key => value, ..., key => value);
$blackbook = array("marty" => "206-685-2181",
                   "stuart" => "206-685-9138",
                   "jenny" => "206-867-5309");

foreach loop and associative arrays

foreach ($blackbook as $key => $value) {
    print("$key's phone number is $value\n");
}
jenny's phone number is 206-867-5309
stuart's phone number is 206-685-9138
marty's phone number is 206-685-2181

Associative array functions

Printing an associative array

print_r($blackbook);
Array
(
[jenny] => 206-867-5309
[stuart] => 206-685-9138
[marty] => 206-685-2181
)

Practice problem: Display query parameters

Write a PHP script that will print out all query parameters that are passed to it (their names and their values), similar to http://faculty.washington.edu/stepp/params.php.

Practice problem: Word count

Write a PHP script that counts the most frequently used words in a large text file, such as the text of Hamlet. Print the 10 most frequently used words in the book in descending order as a definition list.

Internal order of arrays

$proverb = array(2 => "haste", 1 => "makes", 0 => "waste");
print_r($proverb);
ksort($proverb);
print_r($proverb);
Array
(
    [2] => haste
    [1] => makes
    [0] => waste
)
Array
(
    [0] => waste
    [1] => makes
    [2] => haste
)

Practice problem: Display query parameters

Write a PHP script that will print out all query parameters that are passed to it (their names and their values), similar to http://faculty.washington.edu/stepp/params.php.

Practice problem: Word count

Write a PHP script that counts the most frequently used words in a large text file, such as the text of Hamlet. Print the 10 most frequently used words in the book in descending order as a definition list.

PHP expression blocks

<?= expression ?>
<h2>The answer is <?= 6 * 7 ?></h2>

The answer is 42


Problem: Ugly PHP string-printing

<?php
print("<ul>\n");
for ($i = 10; $i > 0; $i--) {
    print("<li class=\"c1\"> $i bottles of beer</li>\n");
    print("<li class=\"c2\"> take one down,
                             pass it around</li>\n");
}
print("</ul>\n");
?>

Advanced PHP expression blocks

<ul>
<?php for ($i = 10; $i > 0; $i--) { ?>

  <li class="c1"> <?= $i ?> bottles of beer</li>
  <li class="c2"> take one down, pass it around</li>

<?php } ?>
</ul>