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.
NULL)verb(noun) rather than noun.verb()$ prefix. string concatenation operatorelseif keyword.php or .phtml extensions<?php and end with ?>
.html file (static content): server just sends that file.php file (dynamic content): server reads it, runs any script code inside it, then sends result across the network
<!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>
phpinfo()
<?php
phpinfo();
?>
$name = value;
$username = 'pinkHeartLuvr78'; $age = 16; $thisClassRocks = TRUE; $éléphant = "totally legit variable name";
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!');
echo command instead of print
print("This will print the variable's value: $var");
print('This will print the variable\'s name: $var');
"" are interpreted
' ' are not interpreted# single-line comment // another single-line comment style /* multi-line comment */
# is also allowed
# comments instead of //+ - * / % . ++ -- = += -= *= /= %= == != > < >= <= && || !
== just checks value ("5.0" == 5 is true)=== also checks type ("5" === 5 is false)5 < "7" is true. (the dot character), not +for loopfor (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>");
}
include()include("filename");
include("header.php");
String type$favoriteFood = "ethiopian"; $favoriteFood[2]; # evaluates to "h"
."", variables and escaped chars are interpreted, but not using ''explode, implode, strlen, strcmp, strpos, substr, strtolower, strtoupper, trim
$length = strlen($favoriteFood);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"
| Name | Javascript or Java Name |
|---|---|
explode, implode |
split, join |
strlen |
length |
strcmp |
compareTo |
strpos |
indexOf |
substr |
substring |
strtolower, strtoupper |
toLowerCase, toUpperCase |
trim |
substring |
$piApprox = 355/113; # double: 3.141592920354 (int) $piApprox; # int: 3 round($piApprox); # double: 3
int for integers and double for realsintval() to convert a String into an intint values can have type double$feelsLikeSummer = FALSE; $phpIsRad = True; $studentCount = 96; (bool) $studentCount; # evaluates to TRUE
TRUE and FALSE keywords are case insensitiveFALSE (all others are TRUE):
00.0 (but NOT 0.00 or 0.000!)"" (the empty string) and "0"NULL (includes unset variables)(bool)NULLif/else statementif (condition) { statements; } elseif (condition) { statements; } else { statements; }
elseif keyword is much more common, else if is also supported$DIR = "awesomeFiles"; $dh = opendir($DIR); while ($file = readdir($dh)) { print("$file<br>\n"); } closedir($dh);
opendir() - begins reading a directory and returns a reference to itreaddir() - reads one file name from the directory referenceclosedir() - stops reading the directoryGiven 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.
function name(parameterName, ..., parameterName) { statements; }
function quadratic($a, $b, $c) {
return -$b + sqrt($b*$b - 4*$a*$c) / (2*$a);
}
name(parameterValue, ..., parameterValue);
$root = quadratic(1, $x, $a + 3);
$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 loopforeach (array as $name) { ... }
$stooges = array("Larry", "Moe", "Curly", "Shemp");
foreach ($stooges as $stooge) {
print("<p>Moe slaps $stooge</p>"); # even himself!
}
count : number of elements in the arrayprint_r : print array's contentsarray_pop,
array_push,
array_shift,
array_unshift
array_reverse,
in_array,
rsort,
shuffle,
sort
array_fill,
array_merge,
array_slice,
array_unique,
range
$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")
/, such as "/[AEIOU]+/"preg_match(pattern, string) TRUE if the given string contains the given pattern
i at end of regular expression (after closing / )preg_replace(pattern, replacement, string) preg_split(pattern, string) $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"
$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"); } }
$str after the preg_replace call?$tokens ?
$text = file_get_contents("filename");
$lines = preg_split("/\n/", $text);
foreach ($lines as $line) {
do something with $line;
}
file_get_contents returns entire contents of a file as a large stringpreg_splitfile_set_contents writes a string into a file# 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"));
$_GET and $_POST$cc = $_GET["creditcard"]; # if it is a GET request $username = $_POST["username"]; # if it is a POST request
$_GET["parameter name"] returns the value of the query parameter with that name, if the browser made a GET request$_POST["parameter name"] returns the value of the query parameter with that name, if the browser made a POST request$_GET and $_POST are called associative arrays or maps (seen later)$_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, $_SESSIONif (array_key_exists("creditcard", $_GET)) { $cc = $_GET["creditcard"]; ... } else { print("Error, you did not submit a credit card number."); ... return; }
array_key_exists function returns TRUE if the $_GET or $_POST has a parameter with the given namereturn or exit functionurlencode$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?!"
header function if you need to output other data or result codes
header("Content-type: text/plain");header("Content-type: application/xml");header("HTTP/1.1 400 Invalid Request");header("HTTP/1.1 404 File Not Found");header("HTTP/1.1 500 Server Error");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.
type is list, display an HTML page with the entire contents of the file list.txt.type is meaning, also accept a parameter named name. Search the file meanings.txt for the line associated with that name and display it.type is rank, also accept a parameter named name. Search the file rank.txt for the line associated with that name and display its ranking data as text or as XML.
$autobots = array("Optimus", "Bumblebee", "Grimlock");
$autobots[100] = "Hotrod";
count of 4, with 97 blank elements between "Grimlock" and "Hotrod"$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");
$name = array(key => value, ..., key => value);
$blackbook = array("marty" => "206-685-2181",
"stuart" => "206-685-9138",
"jenny" => "206-867-5309");
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
array_key_exists : returns whether an associative array contains a value associated with the given keyarray_keys, array_values : returns all keys or all values of an associative array as an arrayasort, arsort : sorts an associative array by value, in normal or reverse order respectively
sort on an associative array will destroy the keys and sort the values into integer indexesksort, krsort : sorts an associative array by key, in normal or reverse order respectively
print_r($blackbook);
Array ( [jenny] => 206-867-5309 [stuart] => 206-685-9138 [marty] => 206-685-2181 )
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.
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.
$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
)
foreach) in this orderWrite 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.
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.
<?= expression ?>
<h2>The answer is <?= 6 * 7 ?></h2>
<?= value ?> is equivalent to <?php print(value); ?>
<?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");
?>
printing them can be tedious, error-prone<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>
<?php switches from normal HTML mode to PHP-evaluating mode