1 / 40

PHP

PHP. Chapter 5 Embedded PHP Arrays, Query Strings, Functions, Files, etc. Embedding code in web pages. most PHP programs actually produce HTML as their output dynamic pages; responses to HTML form submissions; etc.

brooklyn
Télécharger la présentation

PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Chapter 5 Embedded PHP Arrays, Query Strings, Functions, Files, etc.

  2. Embedding code in web pages • most PHP programs actually produceHTML as their output • dynamic pages; responses to HTML form submissions; etc. • an embedded PHP program is a file that contains a mixture of HTML and PHP code

  3. A bad way to produce HTML in PHP <?php print "<!DOCTYPE html>\n"; print "<html>\n"; print " <head>\n"; print " <title>Geneva's web page</title>\n"; ... for ($i = 1; $i <= 10; $i++) { print "<p> I can count to $i! </p>\n"; } ?> • printing HTML tags with print statements is bad style and error-prone: • must quote the HTML and escapespecial characters, e.g. \“ • must insert manual \n line breaks after each line • but with less print statements , how do we insert dynamic content into the page?

  4. Syntax for embedded PHP HTML content <?php PHP code ?> HTML content • any contents of a .phpfile that are not between <?phpand ?> are output as pure HTML • can switch back and forth between HTML and PHP "modes"

  5. Embedded PHP + print = bad <!DOCTYPE html> <html> <head> <title>Geneva's web page</title> </head> <body> <h1>Geneva'sCounting Page</h1> <p>Watch how high I can count: <?php for ($i = 1; $i <= 10; $i++) { print "$i\n"; } ?> </p> </body> </html> • the above code would be saved into a file such as count.php • How many lines of numbers will appear? • run it and View Source! • best PHP style is to use as few print/echostatements as possible in embedded PHP code • but without print, how do we insert dynamic content into the page?

  6. PHP expression blocks <?= expression ?> PHP Embedded PHP <h2> The answer is <?= 6 * 7 ?> </h2> OUTPUT • PHP expression block: a small piece of PHP that evaluates and embeds an expression's value into HTML <?= expression ?> is equivalent to: <?php print expression; ?> • useful for embedding a small amount of PHP (a variable's or expression's value) in a large block of HTML without having to switch to "PHP-mode"

  7. Embedded PHP example 1 <!DOCTYPE html> <html> <head><title>CMPS 278: Embedded PHP</title></head> <body> <h1>Geneva'sCounting Page</h1> <p>Watch how high I can count: <?phpfor ($i = 1; $i <= 10; $i++) {?> <?= $i?> <?php}?> </p> </body> </html> <body> <h1>Geneva'sCounting Page</h1> <p>Watch how high I cancount : <br/> <?phpfor ($i = 1; $i <= 10; $i++) {?> <?= $i?> <br/> <?php}?> </p> </body> </html> 7

  8. Embedded PHP example 2 <!DOCTYPE html> <html> <head><title>CMPS 278: Embedded PHP</title></head> <body> <?phpfor ($i = 5; $i >= 1; $i--) { ?> <p> <?= $i ?> bottles on the wall, <br /> <?= $i ?> bottles. <br /> Take one down, pass it around, <br /> <?= $i - 1 ?> bottles on the wall. </p> <?php}?> </body> </html> 8

  9. 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> • </body> and </html> above are inside the for loop, which is never closed • 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 9

  10. Complex expression blocks <body> <?php for ($i = 1; $i <= 3; $i++) { ?> <h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>> <?php } ?> </body> • expression blocks can even go inside HTML tags and attributes 10

  11. Arrays • PHP arrays like other variables, begin with the $ symbol. • Individual array elementsareaccessedby following the array’s variable name with an index enclosed in square brackets ([]). • If a value is assigned to an array that does not exist, then the array is created. • Likewise, assigning a value to an element where the index is omitted appends a new element to the end of the array. • Function countreturns the total number of elements in the array. • Function arraycreates an array that contains the arguments passed to it. • The first item in the argument list is stored as the first array element (index 0), the second item is stored as the second array element and so on.

  12. Arrays PHP $name = array(); # create $name = array(value0, value1, ..., valueN); $name[index] # get element value $name[index] = value; # set element value $name[] = value; # append $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) $a2[20] = "notContiguous!"; # add string to index 20 • After the statement a2[20]= "…", array count is still 6 but elements are not stored contiguously • Next append will start at index 21 • element type is not specified; can mix types

  13. Array function example

  14. 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") • the array in PHP replaces many other collections in Java • list, stack, queue, set, map, ...

  15. The foreachloop Foreach ($arrayName as $elementIndex=> $Elementvalue) Foreach ($arrayName as $Elementvalue) • The foreach statement, designed for iterating through arrays without indexes, • starts with the array to iterate through, • followed by the keyword as, • followed by two variables • the first is assigned the index of the element • the second is assigned the value of that index’s element. • If only one variable is listed after as, it is assigned the value of the array element. $stooges = array("Larry", "Moe", "Curly", "Shemp"); for ($i = 0; $i < count($stooges); $i++) { print "Moe slaps {$stooges[$i]}\n"; } foreach ($stooges as $stooge) { print "Moe slaps $stooge\n"; # even himself! }

  16. The foreachloop • Arrays with nonnumeric indices are called associative arrays. • You can create an associative array using the operator =>, • The value to the left of the operator is the array index • The value to the right is the element’s value. • PHP provides functions for iterating through the elements of an array. • Each array has a built-in internal pointer, which points to the array element currently being referenced. • Function reset : sets the internal pointer to the first array element. • Function key: returns the index of the element currently referenced by the internal pointer, • function next: moves the internal pointer to the next element. $third[ "Amy" ] = 21; $third[ "Bob" ] = 18; $third[ "Carol" ] = 23; $fourth = array( "January“ => "first", "February" => "second“, "March" => "third", "April" => "fourth“, "May“ => "fifth", "June" => "sixth", "July“ => "seventh", "August“ => "eighth", "September" => "ninth", "October“ => "tenth“, "November“ => "eleventh", "December" =>"twelfth“ );

  17. Returns the index of the element being pointed to Moves the internal pointer to the next element and returns it Sets the internal pointer to the first array element in $third

  18. Iterates through each element in array $fourth Stores the index of the element Stores the value of the element

  19. Alternative syntax for control statements <?php if(conditions){ ?> ... HTML CODE ... <?php } ?> <?php while(conditions) { ?> ... HTML CODE ... <?php } ?> <?php for(init;conditions;increment) { ?> ... HTML CODE ... <?php } ?> Change Opening brace { to : • Change closing brace } to • endif; • endwhile; • endfor; • endforeach <?php if(conditions): ?> ... HTML CODE ... <?phpendif; ?> <?php while(conditions) : ?> ... HTML CODE ... <?phpendwhile; ?> <?php for(init;conditions;increment) : ?> ... HTML CODE ... <?phpendfor; ?> 19

  20. Query strings and parameters URL?name=value&name=value... http://www.google.com/search?q=Obama http://example.com/student_login.php?username=Bob&id=1234567 • most server-side web programs acceptparameters that guide their execution • Query strings: 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 Bob, and sid has value 1234567 • PHP code on the server can examine and utilize the value of parameters • PHP code may produce different output based on values passed by the user

  21. Query parameters: $_REQUEST URL?name=value&name=value... $_REQUEST["parameter name"] returns a parameter's value as a string http://example.com/student_login.php?username=Bob&sid=1234567 • Parameter username has value Bob • Parameter sid has value 1234567 $user_name = $_REQUEST["username"]; $id_number = (int) $_REQUEST["id"]; • Superglobalarrays are associative arrays predefined by PHP • hold variables acquired from user input, the environment or the web server • are accessible in any variable scope • $_REQUEST is an superglobalassociative array that by default contains the contents passed to a server via any type of request (query strings, forms, or cookies, etc.)

  22. Functions functionname(parameterName, ..., parameterName) { statements; } function bmi($weight, $height) { $result = 703 * $weight / $height / $height; return $result; } • parameter types and return types are not written • can be declared in any PHP block, at start/end/middle of code

  23. Calling functions name(expression, ..., expression); function bmi($weight, $height) { $result = 703 * $weight / $height / $height; return $result; } $w = 163; # pounds $h = 70; # inches $my_bmi = bmi($w, $h); • if the wrong number of parameters are passed, it's an error • a function with no return statements implicitly returns NULL

  24. Variable scope: global and local vars $school = "AUB"; # global ... function downgrade() { global $school; $suffix = “Beirut"; # local $school = "$school $suffix"; print "$school\n"; } • variables declared in a function are local to that function • variables not declared in a function 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

  25. Default Parameter Values functionname(parameterName = value, ..., parameterName = value) { statements; } function print_separated($str, $separator = ", ") { if (strlen($str) > 0) { print $str[0]; for ($i = 1; $i < strlen($str); $i++) { print $separator . $str[$i]; } } } print_separated("hello"); # h, e, l, l, o print_separated("hello", "-"); # h-e-l-l-o • if no value is passed, the default will be used (defaults must come last)

  26. example http://example.com/exponent.php?base=3&exponent=4 3 ^ 4 = 81 exponent.php $base = $_REQUEST["base"]; $exp = $_REQUEST["exponent"]; $result = pow($base, $exp); print "$base ^ $exp = $result";

  27. PHP file I/O functions

  28. Reading/writing files • file returns lines of a file as an array • file_get_contents returns entire contents of a file as a string • if the file doesn't exist, you'll get a warning

  29. Reading/writing an entire file # reverse a file $text = file_get_contents("poem.txt"); $text = strrev($text); file_put_contents("poem.txt", $text); • file_get_contentsreturnsentire contents of a file as a string • if the file doesn't exist, you will get a warning and an empty return string • file_put_contentswrites a string into a file, replacing its old contents • if the file doesn't exist, it will be created

  30. 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); • file_put_contents can be called with an optional third parameter to append (add to the end) rather than overwrite

  31. The file function # display lines of file as a bulleted list $lines = file("todolist.txt"); foreach ($lines as $line) { # for ($i = 0; $i < count($lines); $i++) print "<li>$line</li>\n"; } • filereturns the lines of a file as an array of strings • each array element ends with \n ; to strip it, use an optional second parameter: • common idiom: foreach or for loop over lines of file $lines = file("todolist.txt", FILE_IGNORE_NEW_LINES); 31

  32. Reading directories • glob can filter by accepting wildcard paths with the * character • glob("foo/bar/*.doc") returns all .doc files in the foo/bar subdirectory • glob("food*") returns all files whose names begin with "food" • glob("lecture*/slides*.ppt") examines all directories whose names begin with lecture and grabs all files whose names begin with "slides" and end with ".ppt" 32

  33. glob example # 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 " . basename($poemfile); } • basename function strips any leading directory from a file path basename("foo/bar/baz.txt") returns"baz.txt" 33

  34. scandir example <ul> <?php $folder = "taxes/old"; foreach (scandir($folder) as $filename) { print "<li>$filename</li>\n" } ?> </ul> • Output . .. 2007_w2.pdf 2006_1099.doc • annoyingly, the current directory (".") and parent directory ("..") are included in the array • don't need basenamewith scandir because it returns the file's names only 34

  35. Unpacking an array: list list($var1, ..., $varN) = array; Marty Stepp (206) 685-2181 570-86-7326 personal.txt list($name, $phone, $ssn) = file("personal.txt"); • the listfunction "unpacks" an array into a set of variables you declare • It accepts a comma-separated list of variable names as parameters • can be assignedfrom an array (or the result of a function that returns an array) • when you know a file's exact length/format, use file and list to unpack it

  36. Example: Print all parameters http://example.com/print_params.php?name=Mr+X&sid=1234567 print_params.php <?phpforeach($_REQUEST as $param => $value) :?> <p>Parameter <?= $param ?> has value <?= $value ?></p> <?phpendforeach;?> Parameter name has value Mr X Parameter sid has value 1234567 • or call print_r or var_dump on $_REQUEST for debugging 36

  37. Including files Include (“filename”); • Inject a file’s contents into your page. • If these contents are HTML code, the code will be part of your page and will be rendered by the browser. • If these contents are PHP code, it will be executed and any variables or functions in the code will be available to any of your subsequent code • It can be used to eliminate redundancy at the file level. • Several pages may have a common header or share common large block of content • place the common content into separate file and have each page include it.

  38. example words.txt prothalamion noun a song in celebration of a marriage atrabilious adjective given to or marked by melancholy; GLOOMY hyacinth noun a precious stone of the ancients sometimes held to be the sapphire; a gem zircon or essonite souse verb pickle pyrrhic adjective costly to the point of negating or outweighing expected benefits orgulous adjective proud jactitation noun a tossing to and fro or jerking and twitching of the body proselytize verb to recruit someone to join one's party, institution, or cause ultima noun last syllable of a word lagniappe noun an extra or unexpected gift or benefit

  39. example words.txt prothalamion noun a song in celebration of a marriage atrabilious adjective given to or marked by melancholy; GLOOMY hyacinth noun a precious stone of the ancients sometimes held to be the sapphire; a gem zircon or essonite souse verb pickle pyrrhic adjective costly to the point of negating or outweighing expected benefits orgulous adjective proud jactitation noun a tossing to and fro or jerking and twitching of the body proselytize verb to recruit someone to join one's party, institution, or cause ultima noun last syllable of a word lagniappe noun an extra or unexpected gift or benefit top.html word.css <!DOCTYPE html> <html> <head> <title>Word of the Day</title> <link href="word.css" type="text/css" rel="stylesheet" /> </head> <body> <h1>GRE Vocab Word of the Day</h1> blockquote { font-style: italic; } body { background-color: white; padding: 1em 1em; font-family: Garamond, serif; font-size: 14pt; } .partofspeech { font-family: monospace; font-weight: bold; }

  40. example word.php <?php include("top.html"); $WORDS_FILENAME = "words.txt"; # reads a random word line from disk and displays its text function read_random_word() { global $WORDS_FILENAME; $lines = file($WORDS_FILENAME); $random_index = rand(0, count($lines) - 1); $random_line = $lines[$random_index]; $tokens = explode("\t", $random_line); list($word, $part, $definition) = $tokens; ?> <blockquote> <p> <?= $word ?> - <span class="partofspeech"><?= $part ?></span>. <br /> <?= $definition ?> </p> </blockquote> <?php } ?> <div> <?php for ($row = 1; $row <= 2; $row++) { for ($col = 1; $col <= 6; $col++) { ?> <img src="vocab.jpg" alt="vocab guy" /> <?php } ?> <br /> <?php } ?> </div> <p>Your word of the day is:</p> <?php read_random_word(); ?> </body> </html>

More Related