JMU
Server-Side PHP Programming
An Introduction with Examples


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


PHP Programs and HTTP Servers
Inserting Output into the HTTP Response
An Example

How Code Fragments are Inserted into this Lecture's Slides

Loading the PHP Classes/Functions

<script language="PHP">
require_once('scripts/codeProcessor.phps');
</script>
  

Insertion of the Code Fragment

<pre>
<script language="PHP">
$code = file('javaexamples/datahiding/Node.java');
processCode($code, ''); // Uses echo and/or printf
</script>
</pre>
  
Another Example

Inserting a "Directory" of (non-PHP) Files

<?php
function createDirectoryListing()
{
  $dir = opendir(".");

  while (($file = readdir($dir)) !== false)
  {
    if ((strpos($file, ".php")) !== false)
    {
	$text = "";
	$code = file($file);

	for ($i=0; $i<count($code); $i++)
	{
	  $text = $text . $code[$i];
	}

	$start = strpos($text, "<title>");
	$end   = strpos($text, "</title>");

	if (($start !== false) && ($end !== false))
	{
	  $length = $end - $start - 7;
	  $title = substr($text, $start+7, $length);
          if ($length > 0)
          {
	    $item[$file] = $title;
          }
	}
      }
  }

  asort($item, SORT_STRING);

  foreach ($item as $file => $title)
  {
      echo "<ul>";
      echo "<a href=\"" . $file . "\">" . $title . "</a>";
      echo "<br />";
      echo "</ul>";
  }
}
?>
  
Getting Information about the Request
Getting Detailed Information about a GET/POST Request
Cookies
Sending Custom Header Information
Some Useful Functions