Week 7 Section: Intro to PHP and Web Services

PHP Review

PHP is a server-side scripting language. We will use it in this class to build web servers clients can request data from in different formats (plain text, JSON, etc.).

Today, we will get more practice writing simple PHP programs. Soon, we will use these basics to create our own fully-functional API!

Here's a handy PHP language cheatsheet and list of common PHP bugs you might find helpful these next few weeks!

Section Agenda

  • Part I: Functions and Simple Arrays
  • Part II: PHP GET Web Services
  • Part III: Web Services with Associative Arrays (Precursor to JSON APIs!)

Part I: Functions and Simple Arrays in PHP

  1. array_mystery
  2. longest_string
  3. switch_pairs (challenge)

(go down to work on these!)

Part I: array_mystery

Consider the following PHP code:

function array_mystery($arr) {
  for ($i = 1; $i < count($arr); $i++) {
    $arr[$i] = $arr[$i] + $arr[$i - 1];
  }
  return $arr;
}

PHP

Indicate in the right-hand column what values would be stored in the returned array after the function array_mystery executes if the array in the left-hand column is passed as a parameter to array_mystery. Include your answers in the format of [a, b, c] where a, b, and c are numbers in the array result (for a 3-element array).

  1. [8] :
  2. [6, 3] :
  3. [1, 2, 3, 4] :
  4. [7, 10, 12, 12, 17] :

Part I: longest_string

You can find the specification for writing the longest_string function on CodeStepByStep here. You may either solve the problem on CSBS (which will run tests for you) or you may write a PHP file called longestString.php and test the solution on the browser with your local server running.

Part I: switch_pairs (challenge problem)

You can find the specification for writing the switch_pairs function on CodeStepByStep here. You may either solve the problem on CSBS (which will run tests for you) or you may write a PHP file called switchPairs.php.

Part II: PHP Web Services

With a server-side language like PHP, we can now write web services like the ones we were clients of in JavaScript. Most of our web services will make use GET requests.

Recall that GET query parameters are those that are passed through the url to a web service. To access GET parameters passed to a PHP web service, we can use the $_GET "superglobal" array.

$name = $_GET["name"];
echo "Hello {$name}!";

PHP

Handling Missing Query Parameters

To respond to GET requests made to our web services, we can't just assume the user passes the correct query parameter. To check whether a parameter has been passed in the URL, we use the isset($val) function, which returns true only if $val is not NULL (in other words, it was passed in the url).

if (isset($_GET["name"])) {
  $name = $_GET["name"];
  echo "Hello {$name}!";
} else {
  echo "Missing required name parameter!";
}

PHP

Exercise: greeter.php

Write a PHP web service greeter.php that takes two parameters, firstname and lastname and outputs a little greeting (in plaintext output). The greeting should be in the format of "Hello, Firstname, L.!" where the first name is title-cased (only the first letter is capitalized) and the last name is replaced with its capitalized first letter.

For example, a call to greeter.php?firstname=aSH&lastname=ketchum should output the message: "Hello, Ash K.!"

If the firstname parameter is missing, print a message "Missing required firstname parameter". Otherwise if the lastname parameter is missing, the printed greeting should be in the format "Hello, Firstname!". You can find a runnable example here.

Exercise: menu.php

Write a PHP web service menu.php that has arrays with a few of your favorite foods ($drinks, $bakery, etc.) and prints a to-string representation of the category based on the value of a GET parameter "category" passed.

For example, a call to menu.php?category=drinks should output the array of drinks: "[coffee, tea, water]" if those are the drinks defined in your web service.

If category is not passed or the value for category does not correspond to one of your categories, output a helpful error message.

You can start with this menu.php file which includes the to_string function we did in lecture yesterday.

menu.php: Solution

One solution can be found here.

Part III: Associative Arrays in PHP

Associative arrays are arrays that have keys with assigned values (similar to Maps in Java, dictionaries in Python, or JSON objects in JS)

$tas = array("AA" => "Connie Wang", "AB" => "Jack Venberg", 
             "AC" => "William Kim", "AD" => "Kelley Chen",
             "AE" => "Sweekruthi Raghunathan", "AF" => "Jeffrey Worley",
             "AI" => "Sven Hansen", "AJ" => "Anupam Gupta",
             "AK" => "Conner Ardman", "AL" => "Andrew Wolfram");
$tas["ZZ"] = "Jeremy Zhang";

PHP

Looping through key/values: the foreach loop

A convenient way to loop over each element of an array without indices!

foreach ($array_name as $value) {
  echo "Found value: {$value}\n";
}

PHP (example)

Alternatively, you can do this when you want to use both the key and value:

foreach ($array_name as $key => $value) {
  echo "The value for the key {$key} is {$value}\n";
}

PHP (example)

Exercise: tas.php

Using the starter PHP file tas.php which defines the associative array of TA's from the previous slide, implement the program as a PHP web service to associate TA's with their section code (and vice versa).

You can try the running solution here (note that it handles case-insensitivity!)

tas.php (1/2)

First, we'll handle one of two possible GET parameters in our web service.

If a GET parameter section is passed, output the full name of the TA who teaches that section (ignoring letter casing). If the section does not exist in the $tas array, print an error message, "Passed section code not found.".

Hint: To check if a key $key exists in an associative array $arr, you can use:


if ($arr[$key]) { 
  ...
}

PHP

When you're done, move on to Part 2 on the slide below.

tas.php Part 2

Next we'll handle a second option for our web service. If a GET parameter name is passed, output the section code for the TA who the passed value as their first name (ignoring letter-casing). If no TA has the first name, print an error message, "No TA found with given first name".

tas.php: Solution

You can find a solution here (with example PHP documentation)