400 likes | 487 Views
CMPT241 Web Programming. More on PHP: Arrays, Functions and Files. best PHP style is to minimize print/echo statements in embedded PHP code but without print, how do we insert dynamic content into the page ?. Printing HTML tags in PHP = bad style. <? php print "<!DOCTYPE html>"<br>";
E N D
CMPT241 Web Programming More on PHP: Arrays, Functions and Files
best PHP style is to minimize print/echo statements in embedded PHP code but without print, how do we insert dynamic content into the page? Printing HTML tags in PHP = bad style <?php print "<!DOCTYPE html>"\n"; print " <head>\n"; print " <title>My web page</title>\n"; ... for ($i = 1; $i <= 10; $i++) { print "<p> I can count to $i! </p>\n"; } ?> HTML
PHP expression block: a small piece of PHP that evaluates and embeds an expression's value into HTML • <?= expression ?> is equivalent to: PHP expression blocks <?= expression ?>PHP <h2> The answer is <?= 6 * 7 ?> </h2>PHP The answer is 42 output <?php print expression; ?>PHP
Expression block example <!DOCTYPE html> <head><title>Embedded PHP</title> </head> <body> <?php for ($i = 99; $i >= 1; $i--) { ?> <p> <?= $i ?> bottles of beer on the wall, <br /> <?= $i ?> bottles of beer. <br /> Take one down, pass it around, <br /> <?= $i - 1 ?> bottles of beer on the wall. </p> <?php } ?> </body> </html>PHP
if you forget to close your braces, you'll see an error about 'unexpected $end' if you forget = in <?=, the expression does not produce any output Common errors: unclosed braces, missing = sign ... <body> <p>Watch how high I can count: <?php for ($i = 1; $i <= 10; $i++) { ?> <?$i ?> </p> </body> </html>PHP
Complex expression blocks ... <body> <?php for ($i = 1; $i <= 3; $i++) { ?> <h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>> <?php } ?> </body>PHP This is a level 1 heading. This is a level 2 heading. This is a level 3 heading.output
Append:use bracket notation without specifying an index Element type is not specified; can mix types Arrays $name = array(); # create $name = array(value0, value1, ..., valueN); $name[index] # get element value $name[index] = value; # set element value $name[] = value; # appendPHP $a = array(); # empty array (length 0) $a[0] = 23; # stores 23 at index 0 (length 1) $a2 = array("some", "strings", "in", "an", "array"); $a2[] = "Ooh!"; # add string to end (at index 5)PHP
Arrays $a2 = array("some", "strings", "in", "an", "array"); $a2[100] = "Ooh!"; # add string to end (at index 100) PHP
the array in PHP replaces many other collections in Java • list, stack, queue, set, map, ... Array function example $tas = array("MD", "BH", "KK", "HM", "JP"); for ($i = 0; $i < count($tas); $i++) { $tas[$i] = strtolower($tas[$i]); } $morgan = array_shift($tas); array_pop($tas); array_push($tas, "ms"); array_reverse($tas); sort($tas); $best = array_slice($tas, 1, 2); # subarrayPHP
foreach loop foreach ($array as $variableName) { ... }PHP for ($i = 0; $i < count($fellowship); $i++) { print "$fellowship[$i]\n"; } foreach ($fellowship as $fellow) { print "$fellow\n"; }PHP You cannot use a foreach loop to modify the elements
Splitting/joining strings $array = explode(delimiter, string); $string = implode(delimiter, array);PHP • explode and implode convert between strings and arrays $s = “MC CMPT 241"; $a = explode(" ", $s); # ("MC", “CMPT", “241") $s2 = implode("...", $a); # “MC...CMPT...241"PHP
Example with explode Marty D Stepp Jessica K Miller Victoria R Kirstcontents of input file names.txt • explode and implode convert between strings and arrays • foreach (file("names.txt") as $name) { • $tokens = explode(" ", $name); • ?> • <p> author: <?= $tokens[2] ?>, <?= $tokens[0] ?> </p> • <?php • }PHP author: Stepp, Marty author: Miller, Jessica author: Kirst, Victoriaoutput
the list function accepts a comma-separated list of variable names as parameters use this to quickly "unpack" an array's contents into several variables Unpacking an array: list list($var1, ..., $varN) = array;PHP $values = array(“mundruid", "18", “f”); ... list($username, $age, $gender) = $values;PHP
Example explode Harry Potter, J.K. Rowling The Lord of the Rings, J.R.R. Tolkien Dune, Frank Herbert contents of input file books.txt <?phpforeach (file(“books.txt") as $book) { list($title, $author) = explode(“,", $book); ?> <p> Book title: <?= $title ?>, Author: <?= $author ?> </p> <?php } ?> PHP
For this exercise, you will use a list of ten of the largest cities in the world. (Please note, these are not the ten largest, just a selection of ten from the largest cities.) Create an array with the following values: Tokyo, Mexico City, New York City, Mumbai, Seoul, Shanghai, Lagos, Buenos Aires, Cairo, London. Print these values to the browser separated by commas, using a loop to iterate over the array. Sort the array, then print the values to the browser in an unordered list, again using a loop. Add the following cities to the array: Los Angeles, Calcutta, Osaka, Beijing. Sort the array again, and print it once more to the browser in an unordered list. PHP Arrays Exercise
Multidimensional Arrays <?php $AmazonProducts = array( array(“BOOK", "Books", 50), array("DVDs", “Movies", 15), array(“CDs", “Music", 20)); for ($row = 0; $row < 3; $row++) { for ($column = 0; $column < 3; $column++) { ?> <p> | <?= $AmazonProducts[$row][$column] ?> <?php } ?> </p> <?php } ?> PHP
parameter types and return types are not written a function with no return statements implicitly returns NULL can be declared in any PHP block, at start/end/middle of code Functions • function name(parameterName, ..., parameterName) { • statements; • }PHP function bmi($weight, $height) { $result = 703 * $weight / $height / $height; return $result; }PHP
if the wrong number of parameters are passed, it's an error Calling functions name(expression, ..., expression);PHP $w = 163; # pounds $h = 70; # inches $my_bmi = bmi($w, $h);PHP
Any parameters with default values must appear at the end of the list if no value is passed, the default will be used Default Parameter Values function print_separated($str, $separator = ", ") { if (strlen($str) > 0) { print $str[0]; for ($i = 1; $i < strlen($str); $i++) { print $separator . $str[$i]; } } }PHP print_separated("hello"); # h, e, l, l, o print_separated("hello", "-"); # h-e-l-l-oPHP
Value vs. Reference Parameters function make_bigger($num){ $num = $num * 2; } $x = 5; make_bigger($x); print $x;PHP function make_bigger(&$num){ $num = $num * 2; } $x = 5; make_bigger($x); print $x; PHP
variables declared in a function are local to that function; others are global • if a function wants to use a global variable, it must have a global statement • but don't abuse this; mostly you should use parameters Variable scope: global and local vars $dept= “CMPT"; # global ... function course_number() { global $dept; $suffix = “241"; # local $course = $dept. $suffix; print "$course“; }PHP
Note • PHP has no narrower scope than function-level. • Variables are destroyed when the function returns • Variable scope is completely unrelated to the start and end of PHP <?php ... ?> blocks. function scope_example(){ for ($i = 0; $i < 10; $i++){ print “Hello”; $x = 42; } print $i; print $x; }PHP
file_get_contentsreturns entire contents of a file as a string file_put_contentswrites a string into a file, replacing any prior contents Reading from/Writing to a file # reverse a file $text = file_get_contents("poem.txt"); $text = strrev($text); file_put_contents("poem.txt", $text);PHP
file_get_contents • If the file doesn’t exist, an empty string is returned and a warning is issued. • Suppress the warning message • @file_get_contents
Appending to a file # add a line to a file $new_text = "P.S. ILY, GTG TTYL!~"; file_put_contents("poem.txt", $new_text, FILE_APPEND);PHP
Reading files • filereturns lines of a file as an array • file_get_contentsreturns entire contents of a file as a string
file returns the lines of a file as an array of strings • each string ends with \n • to strip the \n off each line, use optional second parameter: The file function # display lines of file as a bulleted list $lines = file("todolist.txt"); foreach ($lines as $line) { ?> <li> <?= $line ?> </li> <?php } ?>PHP $lines = file("todolist.txt",FILE_IGNORE_NEW_LINES);PHP
Example for scandir <ul> <?php $folder = "taxes/old"; foreach (scandir($folder) as $filename) { ?> <li> <?= $filename ?> </li> <?php } ?> </ul>PHP • . • .. • 2009_w2.pdf • 2007_1099.doc output
glob can match a "wildcard" path with the * character Example for glob # reverse all poems in the poetry directory $poems = glob("poetry/poem*.dat"); foreach ($poems as $poemfile) { $text = file_get_contents($poemfile); file_put_contents($poemfile, strrev($text)); print "I just reversed " . }PHP
Insert the content of one PHP file into another PHP file before the server executes it • Use the • include() generates a warning if file not found, but the script will continue execution • require() generates a fatal error, and the script will stop PHP Include File
include() example <a href="/default.php">Home</a> <a href="/tutorials.php">Tutorials</a> <a href="/references.php">References</a> <a href="/examples.php">Examples</a> <a href="/contact.php">Contact Us</a> HTML/PHP <html> <body> <div class="leftmenu"> <?phpinclude("menu.php"); ?> </div> <h1>Welcome to my home page.</h1> <p>I have a great menu here.</p> </body> </html> PHP
query string: a set of parameters passed from a browser to a web server • often passed by placing name/value pairs at the end of a URL • above, parameter username has value stepp, and sid has value 1234567 • PHP code on the server can examine and utilize the value of parameters • a way for PHP code to produce different output based on values passed by the user Query strings and parameters URL?name=value&name=value...PHP http://www.google.com/search?q=Obama http://example.com/student_login.php?username=stepp&id=1234567PHP
$_GET["parameter name"] returns a parameter's value as a string test whether a given parameter was passed with isset Query parameters: $_GET $user_name = $_GET["username"]; $id_number = (int) $_GET["id"]; $eats_meat = FALSE; if (isset($_GET["meat"])) { $eats_meat = TRUE; }PHP
Snoopy Server • Copy the public_html folder from home.manhattan.edu server to your local drive • Upload the whole folder to snoopy.rlc.manhattan.edu using • SSH (Windows) • downloadable from class web page • FileZilla Client (All platforms), which will be installed in the labs
Homework • You may view your page at snoopy.rlc.manhattan.edu/~Your_ID/index.html • You shouldn’t use the examples demonstrated in class. • Homework 6 by the end of the week
Homework 6 • .php page • supporting .css file • Must at least use arrays and files • Something similar to the case study (GRE word of the day) we did in class
Final Project • Team members • Up to 3 people in a team • Decided by Monday • Start thinking about what project you want to work on • Must use PHP, CSS and JavaScript • Client-based? • Proposal due around April 17