1 / 25

PHP

PHP. Application Overview and Example May 27, 2004 Presented By: Mark Armstrong and Marc Saccucci. PHP Benefits. Not proprietary Fast - 10-50% faster then other HTML embedded scripting (CGI) Stable Familiar – syntactically similar to Java/Perl/C/C++

rona
Download Presentation

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 Application Overview and Example May 27, 2004 Presented By: Mark Armstrong and Marc Saccucci

  2. PHP Benefits • Not proprietary • Fast - 10-50% faster then other HTML embedded scripting (CGI) • Stable • Familiar – syntactically similar to Java/Perl/C/C++ • Compatible with nearly all platforms • Dynamic

  3. How PHP Works • Uses Apache Web Server, which handles HTTP requests and sends HTML responses to the browser. • Apache can be configured to render .php files as HTML.

  4. Dynamic Applications • Database access (MySQL, INFORMIX, Oracle, etc) • Text File I/O • XML • Parsing other websites

  5. Embedded in HTML Code All code in one location Fast Scaleable Not compiled Separate CGI script loaded for each request, called by HTML page Slow Not very scaleable PHP vs. CGI

  6. PHP Syntax • Start and end tags needed: <?php PHP Code Here; ?> • Syntactically very close to C • Semicolon after each PHP statement • Comments start with // or # • Variables preceded with a $ • Can be object oriented

  7. GET and POST Form Actions • Used to pass information to a page • POST method is used when passing ‘hidden’ information via forms • GET method is used to create a query string which passes variables via the URL • POST can pass an unlimited amount of data • GET can only pass up to a 1,000 character query string

  8. Query Strings • Use the GET method to pass query strings via the URL. - Example: http://www.weather.gov/forecasts/graphical/sectors/marylandWeek.php?page=1&element=Wx $_GET[“page”]=1 and $_GET[“element”]=Wx is used in the php code to grab the page number and weather element type from the URL above.

  9. Main Code: display_consistency.php <html> <head> <title> Consistency Summary Page </title> <link rel="stylesheet" type="text/css" href="../style.css"> </head> <body leftmargin="0" topmargin="0" rightmargin="0" bgcolor="#FFFFFF"> <!– Start PHP Header --> <?php include'../includes/header.php'; ?> <!-- End Header. Back to HTML. --> <table width="800" border="0" cellspacing="2"> <tr> <td valign="top"> <!-- Left Navigation/Spacer Region --> <!– place holder for leftnav.php -- > &nbsp; <!-- Left Navigation/Spacer Region --> </td> <td valign="top"> <!-- Begin Content area --> Description: First, we’ll create the basic HTML header and open the php code block with the <?php to include the header for the page. Example Application of PHP

  10. display_consistency.php - continued <?php /******************************** * This page displays consistency data for the specified day, neighboring wfo or element specified as spec in the querystring, and the wfo sent in the querystring. ********************************/ // Set up basic parameters and querystring values. $cycle = "hourly"; // variables are always preceded by a $ $wfo=$_GET["wfo"]; // $_Get array contains the form values $spec=$_GET["spec"]; // _GET method and querystrings. // Set the region based on the WFO ID. // The substr function retrieves a substring of the string variable // passed in. In this case, the first character from $wfo is extracted. if ((substr($wfo,0,1) == "K") || $wfo == "CONUS") $region="CONUS"; else $region="ALASKA"; Description: Open PHP using: <?php, and start to set some of the variables that will be needed. We fetch the “wfo” and “spec” parameters from the querystring. Notice the C-style comments and if construct

  11. display_consistency.php - continued // Set up arrays for menu bar items… // using the array() function is one way to // initialize arrays $elementList=array("MaxT","MinT","PoP12","QPF","Sky","SnowAmt","T","Td","WaveHeight", "WindDir","WindSpd"); $day_list=array("Day0","Day1","Day2","Day3", "Day4","Day5","Day6","Day7"); // Like most scripting languages, PHP can use the // echo command to output data. // PHP also uses C output commands as well. // The "." concatenates strings echo "<br><center><h3>Consistency Summary for the $cycle cycle for " . $wfo . "</h3></center>\n"; echo "<center><a href=\"consistency_summary_display.php?wfo=" . $wfo . "\"><< Back to Summary </a></center><br>\n"; Description: Next we set up some arrays using the array() function. We then use php to echo some html code. There is a shortcut for writing out larger blocks of HTML code, or we could just close the PHP block and reopen it after the HTML is written. We copy the correct array to the menu_array when we determine what ‘spec’ is.

  12. display_consistency.php - continued // Include function to determine a WFO // list for the menu. // The source code for any function that you // want to use must be included before you call // the function. include ("get_wfo_list.php"); // Select which menu array to display // Arrays may simply be assigned to each // other as in the next few lines. if (substr($spec,0,1) == "D") $menu_array=$day_list; else if (substr($spec,0,1) == "K" || substr($spec,0,2) == "PA") $menu_array=get_wfo_list($wfo); else $menu_array=$elementList; Description: We copy the correct array to the menu_array when we determine what spec is.

  13. display_consistency.php – continued // Display the menu bar and highlight the // current WFO/Element/Day // the count() function returns the array length echo "<table align=\“center\” boder=\“1\” cols=“ . count($menu_array) . "width=\"500\"> \n<TR>"; for ($i=0; $i<count($menu_array); $i++){ if ($spec == $menu_array[$i]){ echo "<td bgcolor=\"red\">"; } else{ echo "<td bgcolor=\"#98b1d3\">"; } echo "<a href=display_consistency.php?wfo=“ . $wfo . "&spec=" . $menu_array[$i] . "> <center><span class=\"biglinkyellow\">" . $menu_array[$i] . "</span> </center></a></td>\n"; } // End of for loop echo "</tr></table><br>\n"; Description: Now we create a small, one-row table to display the “menu”. We start by using PHP to echo out the table header. We then loop through the menu array that we assigned earlier. If the current spec is the same as the array element, then it is highlighted so we know which Day/WFO/element we are looking at. We create a link for each item in the menu array. The link is the name of this PHP page, with the spec set to each item in the menu array. Lastly, we close the row and the table.

  14. display_consistency.php - continued // Include function that reads the consistency file and // loads the values. include("readConsistencyFile.php"); // Here, we cut some corners for this function. We use // the wfo name and cycle identifier to specify a file that // this function reads. Then we return the information // read here to global variables specified in the function. $status=readConsistencyFile($wfo,$cycle); if($status == -1) echo "Error on page. Please try again"; else if ($status == -10) echo "<center><p><h2>No valid data for this element at this time“ . "</h2></p></center>\n"; else{ echo "<center><span class=\"black\"> Click on each Column Heading “ . "to Sort by that Item </span></a></center><br>\n"; echo "<center><a href=\"../supplementalpages/check_explain.php\">" . "Explanation of statistics and methodolgy used.</a></center><br>\n"; // Include segment of code to display the sortable tables // This is just a large repetitive section of code that // was easier to keep in its own .php file and include it // when needed. include("HourlyTables.php"); } ?> // Close PHP section Description: We need to use a function to read the text file that contains the data. To do this, we need to include the function’s source code. Then, we call the function and pass in two input variables and assign the functions return value to $status for error checking. If there is an error, we output a message to the browser. Then we write out some basic text to the screen. The include at the bottom of the page is simply a space-saver. There are a number of lines of code, which are rather repetitive, which I just dumped into an include file.

  15. display_consistency.php - continued   <br><center>   <table border=“2” cellpadding=“5” width="400">   <tr>   <td align=“center” bgcolor="#C5D5F3"> <span class="black">    Table Created: // Display the time that the table was created.    <?php     $inc_fname="CONTENTS/" . $region . "_hourly_stats_time.php";     include($inc_fname);    ?>    </span></td></tr></table><br> <!-- End Content area -->   </td> </tr> <tr> <td> <!-- Left Navigation/Spacer Region -->   &nbsp; <!-- Left Navigation/Spacer Region -->   </td>   <td> <!-- Start Footer. This is the standard NDFD footer. -->   <?php include'../includes/footer.php'; ?> <!-- End Footer -->   </td> </tr></table> </body> </html> Description: At the end of the page, we have a small table that displays the page’s creation time. The PHP script includes the “hourly_stats_time.php” file, which just contains the generation time. At the very end, the “footer.php” file is included. This contains the generic footer information. We then close the HTML like we normally do.

  16. Function: readConsistencyFile.php <?php function readConsistencyFile($wfo_id,$cycle){ // These are the global variables alluded to elsewhere. global $wfo2, $element, $day, $validTime, $numPts, $thresh, $elevDiff, $avgDiff, $bias, $offset1, $offset2, $mosaicImgName, $discImgName, $facefile, $element; if ($cycle == "hourly"){ $filename=$cycle . "/" . $wfo_id . "_consistency.php"; } else{ $filename=$cycle . "/" .$wfo_id ."_" .$cycle . "_consistency.html"; } // Once again, this is the same type of format as C. // $fp is a file pointer that is returned with a value of // NULL if the file cannot be opened. // Here, we open $filename for reading. $fp=fopen($filename,"r"); if (!$fp) return -1; Description: The function declaration is basically the same as C, without the variable types. The function is contained in the {}. Like other languages, we can declare function variables as global, meaning they can be used anywhere else without passing them in and out of the function. This was done here simply for convenience.

  17. readConsistencyFile.php – continued $i=0; // We read from this file until there is no more data while(!feof($fp)){ if ($cycle == "hourly"){ // read 5 strings, 1 int, 4 floats, // 2 ints and 2 strings from this row $line=fscanf($fp,"%s%s%s%s%s%d%f%f%f%f%d%d%s%s"); // If we can't read this data, continue to the next iteration if ($line == NULL) continue; // list takes line and assigns each value to the specified variable. // We load the associative array elements for sorting purposes later list($wfo2_row, $element_row, $day_row, $ymd_row, $hr_row, $numPts["n$i"], $thresh["n$i"], $elevDiff["n$i"], $avgDiff["n$i"], $bias["n$i"], $offset1["n$i"], $offset2["n$i"], mosaicImgName["n$i"], $discImgName["n$i"]) = $line; Description: We read in data until the end-of-file. The data is fetched, via fscanf into the string variable $line. $line is then broken up into its component variables.

  18. readConsistencyFile.php – continued // trim removes a trailing comma from each string variable $wfo2["n$i"]=trim($wfo2_row,","); $day["n$i"]=trim($day_row,","); $element["n$i"]=trim($element_row,","); $validTime["n$i"]=$ymd_row . " " . trim($hr_row,","); if ($avgDiff["n$i"] > $thresh["n$i"]) $facefile["n$i"]="../staticimages/frown.gif"; else $facefile["n$i"]="../staticimages/smile.gif"; } else{ } $i++; } if ($i == 0){ // didn't read any data, return an error code return -10; } fclose($fp); return 0; } ?> Description: The associative arrays are then loaded. After all of the data is read, the file is closed and we return to calling routine

  19. Function: HourlyTables.php <table cols=13 border=1 bgcolor="silver"> <tr bgcolor="DeepSkyBlue"><span class="black"> <?php if($spec[0] != "K" && substr($spec,0,2) != "PA"){ ?> <td><form method="POST" action="display_consistency.php?cycle=<?="$cycle"?>&wfo=<?="$wfoName"?>&spec=<?="$spec"?>"> <center><input type=submit name="OrderWFO" value="WFO"></center></td> <?php } if ($spec[0] == "K" || substr($spec,0,2) == "PA" || $spec[0] == "D"){ ?> <td><form method="POST" action="display_consistency.php?cycle=<?="$cycle"?>&wfo=<?="$wfoName"?>&spec=<?="$spec"?>"> <center><input type=submit name="OrderElement" value="Element"></center></td> Description: This .php file is included by display_consistency.php. It contains the sortable table. The sortable table has html forms for each column heading that sets the $_POST[“column heading”] variable. Later in the code, the value of each of these variables is checked, and if one is not NULL, the table is sorted by that column. First, we set up the basic HTML table. Then we create the forms for each column heading. It appears simply as submit button with the column name inside it. The if statements are used to selectively output the right headings, since they differ depending upon $spec.

  20. HourlyTables.php – continued <?php } if($spec[0] != "D"){ ?> <!-- Notice how we move into and out of php, even in the middle of if constructs --> <td><form method="POST" action="display_consistency.php?cycle=<?="$cycle"?>&wfo=<?="$wfoName"?>&spec=<?="$spec"?>"> <center><input type=submit name="OrderDay" value="Day"></center></td> <?php } if ($spec[0] == "K" || substr($spec,0,2) == "PA") $thisType="wfo2"; else if($spec[0] == "D") $thisType="day"; else $thisType="element"; // The following html block defines the table headlines // as submit buttons on an HTML form. Clicking the // submit button sorts the data using that column. Description: This is the same type of operation as the previous slide. Notice that even outside of the PHP block, the following HTML code is still contained in the PHP if construct.

  21. HourlyTables.php - continued <td><form method="POST" action="display_consistency.php?cycle=<?="$cycle"?>&wfo=<?="$wfoName"?>&spec=<?="$spec"?>"> <center><input type=submit name="OrderTime" value=" Valid Time "></td> <td><form method="POST" action="display_consistency.php?cycle=<?="$cycle"?>&wfo=<?="$wfoName"?>&spec=<?="$spec"?>"> <center><input type=submit name="OrderFace" value="Approval"></td> <td><form method="POST" action="display_consistency.php?cycle=<?="$cycle"?>&wfo=<?="$wfoName"?>&spec=<?="$spec"?>"> <center><input type=submit name="OrderNumPts" value="Points"></td> <td><form method="POST" action="display_consistency.php?cycle=<?="$cycle"?>&wfo=<?="$wfoName"?>&spec=<?="$spec"?>"> Description: This is the remainder of the column headings/forms. These columns are always present. A few have omitted…

  22. HourlyTables.php - continued <?php // Main array that will be sorted $mainArray = array(); if ($_POST["OrderWFO"]){ // Now we use the _POST array to access the // post data sent to this page // Notice that the associative index of the // _POST array is the "name" of the HTML form // input statement // array_multisort sorts using two arrays: // wfo and validTime array_multisort($wfo2,$validTime, SORT_REGULAR); $mainArray=$wfo2; } else if ($_POST["OrderElement"]){ // here we just sort using one asociative array // (meaning each element is refernced by a unique // string rather than a number) asort($element,SORT_REGULAR); $mainArray=$element; } else{ asort($facefile,SORT_REGULAR); $mainArray=$facefile; } Description: If the $_POST[“”] variable for any of the columns is not NULL, the main_array is set to that columns array. The main array is later sorted, re-arranging the values in the array, but also re-arranging the associative indexes of all of the arrays. Once again, each column heading is tested for, but for simplicity, some are omitted.

  23. HourlyTables.php – cont $count=0; // By having all of these arrays with the same // index names, we can keep all of the corresponding // arrays together even after sorting any one of them. foreach ($mainArray as $key => $val){ // Select which rows to print out. if ($thisType == "wfo2"){ $comp=$wfo2[$key]; if ($comp == $spec){ echo "<tr><span class=\"black\"><center><td>". $element[$key] ."</td><td> {$day[$key]} </td>"; echo "<td> {$validTime[$key]} </td> " . "<td align=\"center\"><img src=\"". $facefile[$key] . "\" width=\"18\" height=\"18\"></td>" . "<td> {$numPts[$key]} </td><td> " . "{$thresh[$key]} </td><td> {$elevDiff[$key]} </td><td> " . "{$avgDiff[$key]} </td><td> {$bias[$key]} </td><td> {$offset1[$key]} " . "</td><td> {$offset2[$key]} </td></center></span></tr>\n"; } } Description: We then loop through the main_array. The foreach construct is a useful way to do that. Once again, we need to selectively print out the data, hence the if ($thisType… statements. We then output the data in HTML format.

  24. HourlyTables.php – continued else{ $comp=$day[$key]; if ($comp == $spec){ echo "<tr><span class=\"black\"><center><td>" . $wfo2[$key] . " </td><td> {$element[$key]} </td>"; echo "<td> {$validTime[$key]} </td> “ . "<td align=\"center\"><img src=\"" . $facefile[$key] . "\" width=\"18\" height=\"18\"></td>“ . "<td> {$numPts[$key]} </td><td> " . "{$thresh[$key]} </td><td> {$elevDiff[$key]} </td><td> " . "{$avgDiff[$key]} </td><td> {$bias[$key]} </td><td> {$offset1[$key]} " . "</td><td> {$offset2[$key]} </td></center></span></tr>\n"; } } } ?> </table> Description: This outputs the data for the other options, one of which was left out in the slide.

  25. PHP Resources • PHP.net – http://www.php.net/manual/en/ • One stop shop for almost any PHP information. • WebMonkey - http://hotwired.lycos.com/webmonkey/programming/php/ • Contains more specific (and obscure) applications of PHP. http://ndfd-dev.weather.gov/forecasts/graphical/MDL_DEMO/display_consistency.php?cycle=hourly&wfo=KLWX&spec=Td

More Related