cmpt241 web programming more on php: arrays, functions and files

41
CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Upload: wesley-perry

Post on 26-Dec-2015

227 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

CMPT241 Web ProgrammingMore on PHP:Arrays, Functions and Files

Page 2: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

2

Printing HTML tags in PHP = bad style

<?phpprint "<!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

• 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?

Page 3: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

3

PHP expression blocks

• PHP expression block: a small piece of PHP that evaluates and embeds an expression's value into HTML▫ <?= expression ?> is equivalent to:

<?= expression ?> PHP

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

The answer is 42

output

<?php print expression; ?>

PHP

Page 4: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

4

Expression block example<!DOCTYPE html><head><title>Embedded PHP</title></head><body><?phpfor ($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

Page 5: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

5

Common errors: unclosed braces, missing = sign...<body><p>Watch how high I can count:<?phpfor ($i = 1; $i <= 10; $i++) {?>

<? $i ?></p></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

Page 6: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

6

Complex expression blocks...<body><?phpfor ($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

Page 7: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

7

Arrays

• Append: use bracket notation without specifying an index

• Element type is not specified; can mix types

$name = array(); # create$name = array(value0, value1, ..., valueN);$name[index] # get element value$name[index] = value; # set element value$name[] = value; # append PHP$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

Page 8: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

8

Arrays

$a2 = array("some", "strings", "in", "an", "array");$a2[100] = "Ooh!"; # add string to end (at index 100)

PHP

Page 9: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

9

Array functionsfunction name(s) description

count(a) number of elements in the array

print_r (a) print array's contents

array_pop(a), array_push(a,value), array_shift(a), array_unshift(a,value)

using array as a stack/queue

in_array(value,a), array_search(value,a), array_reverse(a), sort(a), rsort(a), shuffle(a)

searching and reordering

array_merge(a1,a2,...), array_intersect(a1,a2,...), array_diff(a1,a2), array_slice(a,start,len)

creating, filling, filtering

array_sum(a), array_product(a), array_unique(a) processing elements

Page 10: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

10

Array function example

• the array in PHP replaces many other collections in Java▫ list, stack, queue, set, map, ...

$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); # subarray

PHP

Page 11: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

11

foreach loopforeach ($array as $variableName) {

...} PHPfor ($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

Page 12: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Splitting/joining strings

•explode and implode convert between strings and arrays

$array = explode(delimiter, string);$string = implode(delimiter, array);

PHP

$s = “MC CMPT 241";$a = explode(" ", $s); # ("MC", “CMPT", “241")$s2 = implode("...", $a); # “MC...CMPT...241"

PHP

Page 13: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Example with explode

•explode and implode convert between strings and arrays

Marty D SteppJessica K MillerVictoria R Kirst

contents of input file names.txtforeach (file("names.txt") as $name) {

$tokens = explode(" ", $name);?><p> author: <?= $tokens[2] ?>, <?= $tokens[0] ?> </p><?php} PHPauthor: Stepp, Martyauthor: Miller, Jessicaauthor: Kirst, Victoria

output

Page 14: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

14

Unpacking an array: list

list($var1, ..., $varN) = array; PHP

• 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

$values = array(“mundruid", "18", “f”);...list($username, $age, $gender) = $values;

PHP

Page 15: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

15

Example explodeHarry Potter, J.K. RowlingThe Lord of the Rings, J.R.R. TolkienDune, Frank Herbert

contents of input file books.txt

<?php foreach (file(“books.txt") as $book) {list($title, $author) = explode(“,", $book);?><p> Book title: <?= $title ?>, Author: <?=

$author ?> </p><?php} ?> PHP

Page 16: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

16

PHP Arrays Exercise• 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.

Page 17: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

17

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

Page 18: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

18

Functionsfunction name(parameterName, ..., parameterName) {

statements;} PHP

function bmi($weight, $height) { $result = 703 * $weight / $height / $height; return $result;} 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

Page 19: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

19

Calling functionsname(expression, ..., expression);

PHP

$w = 163; # pounds$h = 70; # inches$my_bmi = bmi($w, $h);

PHP

• if the wrong number of parameters are passed, it's an error

Page 20: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

20

Default Parameter Valuesfunction 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, oprint_separated("hello", "-"); # h-e-l-l-o

PHP

• Any parameters with default values must appear at the end of the list

• if no value is passed, the default will be used

Page 21: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

21

Value vs. Reference Parametersfunction 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

Page 22: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

22

Variable scope: global and local vars

$dept = “CMPT"; # global ...

function course_number() { global $dept; $suffix = “241"; # local

$course = $dept. $suffix; print "$course“; } 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

Page 23: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

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

Page 24: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

24

PHP file I/O functionsfunction name(s) category

file, file_get_contents, file_put_contents

reading/writing entire files

basename, file_exists, filesize, fileperms, filemtime, is_dir, is_readable, is_writable, disk_free_space

asking for information

copy, rename, unlink, chmod, chgrp, chown, mkdir, rmdir

manipulating files and directories

glob, scandir reading directories

Page 25: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

25

Reading from/Writing to a file

• file_get_contents returns entire contents of a file as a string

• file_put_contents writes a string into a file, replacing any prior contents

# reverse a file$text = file_get_contents("poem.txt");$text = strrev($text);file_put_contents("poem.txt", $text); PHP

Page 26: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

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

Page 27: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

27

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

old contents new contents

Roses are red, Violets are blue.

Roses are red, Violets are blue. P.S. ILY, GTG TTYL!~

Page 28: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

28

Reading filescontents of foo.txt

file("foo.txt")file_get_contents("foo.txt")

Hello how are you?

I'm fine

array( "Hello\n", #0 "how are\n", #1 "you?\n", #2 "\n", #3 "I'm fine\n" #4 )

"Hello\n how are\n you?\n \n I'm fine\n"

file returns lines of a file as an array file_get_contents returns entire contents of a

file as a string

Page 29: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

29

The file function

# display lines of file as a bulleted list$lines = file("todolist.txt");foreach ($lines as $line) {

?><li> <?= $line ?> </li>

<?php}?> PHP

• 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:

$lines = file("todolist.txt",FILE_IGNORE_NEW_LINES); PHP

Page 30: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

30

Reading directories

function description

scandir

returns an array of all file names in a given directory (returns just the file names, such as "myfile.txt")

glob

returns an array of all file names that match a given pattern (returns a file path and name, such as "foo/bar/myfile.txt")

Page 31: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

31

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

Page 32: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

32

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

• glob can match a "wildcard" path with the * character

Page 33: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

33

PHP Include File

•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

Page 34: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

34

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"><?php include("menu.php"); ?></div>

<h1>Welcome to my home page.</h1><p>I have a great menu here.</p>

</body></html> PHP

Page 35: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

35

Query strings and parametersURL?name=value&name=value...

PHP

http://www.google.com/search?q=Obama

http://example.com/student_login.php?username=stepp&id=1234567

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

Page 36: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

36

Query parameters: $_GET$user_name = $_GET["username"];$id_number = (int) $_GET["id"];$eats_meat = FALSE;if (isset($_GET["meat"])) { $eats_meat = TRUE;} PHP

• $_GET["parameter name"] returns a parameter's value as a string

• test whether a given parameter was passed with isset

Page 37: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Object Oriented PHP

Page 38: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Case Study

•GRE word of the day

Page 39: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Homework 7

•.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

Page 40: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Project 3

•Due Date: Friday April 3, 2015

Page 41: CMPT241 Web Programming More on PHP: Arrays, Functions and Files

Final Project

•Team members▫Up to 3 people in a team▫Decide by Tuesday March 31

•Start thinking about what project you want to work on▫Must use PHP, CSS and JavaScript▫Proposal is due on April 17.