University of Washington CSE 154

Section 7: Web Services

Except where otherwise noted, the contents of this document are Copyright © Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

IMPORTANT notes this week

Exercise : Animal Gallery (by Alex Miller)

Given a directory of animal pictures (images.zip), write a PHP webpage animals.php which displays these pictures.

If no query parameter is set, then the page should simply display all of the images in the images directory. The user can set an animal query parameter to choose whether to display only puppy pictures, only pony pictures, or only kitty pictures. For example, if the user entered the following URL:

animals.php?animal=puppy

Then the page should only display puppy pictures. The animal parameters that do have photos are kitty, puppy and pony If the user types in a different query parameter that does not have any photos, you should display a message saying that there are no photos for that animal.

Exercise Solution

<!DOCTYPE html PUBLIC>
<html>
  <head>
     <title>Animal Gallery</title>
  </head>
  <body>
    <div>
      <?php
      $animal = "";
      if (isset($_GET["animal"])) {
          $animal = $_GET["animal"];
      }
      $files = glob("images/{$animal}*.jpeg");
      if(count($files) == 0) {?>
         <p> Sorry, looks like we don't have any photos of <?= $animal ?>s.</p>
      <?php } else {
         foreach ($files as $image) {
            ?>
            <img src="<?= $image ?>" alt="animal picture" />
            <?php
         }
      }
      ?>
    </div>
  </body>
</html>

Exercise : Show Links

Write a PHP function show_links in showlinks.php that accepts two parameters: an array of URL strings, and a substring to search for. Display each case-insensitively matching link in a div with a bolded numbering in front.

$links = array("http://www.cs.washington.edu/142/", "http://...");
show_links($links, "CS.Washington.Edu");

The call generates this output (see next slide for screenshot):

<h1>Links to CS.Washington.Edu:</h1>
<div>
	<strong>Site #1:</strong>
	<a href="http://www.cs.washington.edu/142/">http://www.cs.washington.edu/142/</a>
</div>
<div> <strong>Site #2:</strong>...</div>

Exercise Example Output

screenshot
show_links($links,
	"CS.Washington.Edu");

Exercise Solution

<?php
function show_links($links, $site) {  # Displays all URLs from the given
	?>                                  # array that match the given site.
	<h1>Links to <?= $site ?>:</h1>
	<?php
	$site = strtolower($site);
	$count = 0;
	foreach ($links as $url) {
		if (strstr($url, $site)) {
			$count++;
			?>
			<div>
				<strong>Site #<?= $count ?>:</strong>
				<a href="<?= $url ?>"> <?= $url ?> </a>
			</div>
			<?php
		}
	}
}
?>

Exercise : Grades

screenshot

Write a PHP page grades.php that takes a query parameter student and computes total homework points earned by that student. For example, grades.php?student=Marty will read marty.txt. The student input files consist of a single line of scores separated by spaces:

15 14 22 19 13

Print a heading, a bullet list of scores on each assignment, and the total at the bottom. If there is no text file for that student, print "no scores found."

Exercise Solution

<!DOCTYPE html>
<html>
	<head>
		<title>Grades</title>
	</head>
	<body>
		<?php
		$student = "";
		if (isset($_GET["student"])) {
			$student = $_GET["student"];
		}
		?>
		<h1>Grades for <?= $student ?></h1>
		<ul>
			<?php
			$filename = strtolower($student) . ".txt";
			...

Exercise Solution, continued

			if (file_exists($filename)) {
				$total = 0;
				$text = file_get_contents($filename);
				$scores = explode(" ", $text);
				foreach ($scores as $score) {
					$total += $score;
					?>
					<li><?= $score ?> points</li>
				<?php } ?>
				<li>TOTAL: <?= $total ?></li>
			<?php } else { ?>
				<li>no scores found. :-(</li>
			<?php } ?>
		</ul>
	</body>
</html>

Exercise : Calculations (by Alex Miller)

Given an input file input.txt, Write a PHP page calculations.php that reads in the file and calculates the result for each line in the file. For example, the result for the line:

divide:8 2 2

would be:

8 / 2 / 2 = 2

Exercise Solution

<ul><?php
	$lines = file("input.txt");
	foreach ($lines as $line) {
		$split = split(":", $line);
		$numbers = split(" ", $split[1]);
		$sum = $numbers[0];
		for ($i = 1; $i < sizeof($numbers); $i++) {
			if ($split[0] == "add") {
				$sum += $numbers[$i];
			} else if ($split[0] == "multiply") {
				$sum *= $numbers[$i];
			} else if ($split[0] == "subtract") {
				$sum -= $numbers[$i];
			} else if ($split[0] == "divide") {
				$sum /= $numbers[$i];
			}
		} ?>
	<li><?= $line ?> = <?= $sum ?></li>
<?php } ?></ul>
	

Exercise : Show Twos (by Alex Miller)

Write a PHP function show_twos that takes an integer parameter and outputs its factors of 2 with HTML. For example:

show_twos(68);
show_twos(18);
show_twos(68);
show_twos(120);

should produce the following output:

<strong>68</strong> = 2 * 2 * 17<br/>
<strong>18</strong> = 2 * 9<br/>
<strong>68</strong> = 2 * 2 * 17<br/>
<strong>120</strong> = 2 * 2 * 2 * 15<br/>

If you have time, wrap the code in a page that accepts a query parameter num and passes that parameter to the function.

Exercise Solution

<?php
function show_twos($n) { ?>
   <strong><?= $n ?></strong> =
   <?php
   while ($n % 2 == 0) {
      print "2 *";
      $n = $n / 2;
   }
   ?>
   <?= $n ?><br />
   <?php
}

show_twos($_GET["num"]);
?>

Exercise : Chat-It (by Katlyn Edwards)

chatpic

Given this basic skeleton page, add in the necessary form components and PHP to make a minimalistic chat page. You can see a completed version here.

The form needs a place for the user to type in their name, a place for the user to type their message, and a submit button.

The PHP part has two phases. If the page has post data to the form, it should save the data to chat.txt in the following format: name:message\n Remember to set the correct permissions on chat.txt so that the server can write to it.

The other part of the PHP should display the text file into the div with an id of "chatlog". The names should be bold then followed by " says: " and the message. Each message should be it's own paragraph.

Exercise Solution

  <body>
    <?php  
    if(isset($_POST["name"]) && isset($_POST["message"])) {
      file_put_contents("chat.txt", $_POST["name"] . ":" . $_POST["message"] . "\n", FILE_APPEND);
    } ?>
    <div id="chatlog">
       <?php
          $messages = file("chat.txt", FILE_IGNORE_NEW_LINES);
          foreach($messages as $message) {
             $parts = explode(":", $message); ?>
             <p><strong><?= $parts[0] ?></strong> says: &quot;<?= $parts[1] ?>&quot;</p>
          <?php } ?>
    </div>
    <form action="chat.php" method="post">
       Name: <input type="text" name="name" /><br/>
       Message: <input type="text" name="message" /><br/>
       <input type="submit" value="Send!" /> 
    </form>
  </body>