Logo  

CS479/579 - Web Programming II

PHP Examples:

table.php

This example constructs a 10 x 10 table with the row/column position as the data in each cell. Note that is is very similar to the JavaScript example using document.write(). However notice that the dot (.) operator is the string concatenation operator.

<!DOCTYPE html>
<html>
<head>
 <title> Table example </title>
 <meta charset='utf-8'>
</head>
<body>
<table border=1>
<tbody>
<?php
 $rows = 10; $cols = 10;

 for($r = 0; $r < $rows; $r++) {
   echo "<tr>";
   for($c = 0; $c < $cols; $c++) {
     echo "<td>" . $r . ",". $c . "</td>";
   }
   echo "</tr>\n";
 }
?>
</tbody>
</table>
</body>
</html>

errors.php

A script to print the Apache servers' error log in reverse (i.e. most recent error at the top,) but only up to 1MB of records or 100 log lines, whichever is first:

<!DOCTYPE html>
<html>
<head>
 <title> Apache Error log </title>
 <meta charset='utf-8'>
</head>
<body>
<h1> CS server error log </h1>
<pre>
<?php
  $file = "/var/log/httpd/error_log";
  /**
   * If the file is less than 1MB, then read the whole thing, otherwise just
   * read 1MB from the end of the file:
   */
  if (filesize($file) < 1048576) $data = file_get_contents($file);
  else $data = file_get_contents($file, false, NULL, -1048576);

  // Split the file data into an array of lines:
  $lines = explode("\n", $data);
  // Print out the lines from the end of the array of lines:
  for($i=count($lines)-1, $j=0; $i >= 0 && $j < 100 ; $i--, $j++) {
    echo "{$lines[$i]}\n";
  }
?>
</pre>
</body>
</html>

Functions used in the example:

  • filesize()

    • Gets the size of a file in bytes.
  • file_get_contents()

    • Read an entire file into a string (reverse of this function is file_put_contents).
  • explode()

    • Split a string into an array of strings.
  • count()

    • Count the number of elements in an array (or countable)

More on error reporting:

<?php
/**
 * Useful PHP functions to enable PHP error reporting directly through the
 * web browser rather than having to look at the log files:
 */
  // Enable all error reporting:
  error_reporting(E_ALL);
  // Enable the 'display_errors' PHP configuration setting:
  ini_set('display_errors', 1);

  // ... Your code ...

?>

Functions used in the example: