CSE 154

Section 13: 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!

You can also set improved PHP error reporting with MAMP - instructions here.

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 JS. Most of our web services will make use GET requests.

To access GET parameters passed through the URL to a PHP web service, we can use the $_GET "superglobal" array.

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

PHP

Essential Ingredients for a PHP Web Service

  • 1. Checking for missing query parameters with isset
  • Specifying response header options with header:
    • 2. Content type of response output (text or JSON)
    • 3. Error code/messages for invalid requests (usually 400 Invalid Request)

1. Handling Missing Query Parameters with isset

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 is a key found in the $_GET array).

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

PHP

Setting Content Type and Response Errors with header

header is a PHP function to set different information in the response header. In our web services, we will use it to:

  1. Specify the content type of the response (e.g. text/plain)
  2. Specify a 400 error status with status text "Invalid Request"

1. Using header to Set the Output Type

Remember that the default output is HTML, which we don't want in our PHP web services. For now, we're only using plain text as our response type (before any echo/print statements) - later we will learn how to output JSON responses:

header("Content-type: text/plain");
if (isset($_GET["name"])) {
  $name = $_GET["name"];
  echo "Hello {$name}!";
} else {
  echo "Missing required name parameter!";
}

PHP

Inspecting Header Information in Networks Tab

This example shows the default Content-Type as text/html

Inspecting Header Information in Networks Tab

This example shows the result of setting Content-Type as text/plain

and the plain text in the response

Using header to Set Error Response Codes

Remember the 400 errors you've seen as a client (JS) of web services? We also use the header to specify the response code to handle these.

header("Content-type: text/plain");
if (isset($_GET["name"])) {
  $name = $_GET["name"];
  echo "Hello {$name}!";
} else {
  header("HTTP/1.1 400 Invalid Request");
  # This error is also sent as plain text due to the first line
  echo "Missing required name parameter!";
}

PHP

Inspecting Header Information in Networks Tab

This example shows the result of setting the 400 error (note the invalid name2 parameter sent by the client!)

and the plain text in the response (for a more user-friendly error message)

Exercise: greeter.php

Write a PHP web service greeter.php that takes two GET parameters, firstname and lastname and outputs a little greeting (in plain text). The greeting should be in the format of "Hello, Firstname, L.!" where only the first letter of the first name 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, respond with a 400 error 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 defines arrays with a few of your favorite foods ($drinks, $bakery, etc.). When passed a GET parameter "category", this service should print as plain text a bracketed string representation of the array of foods for the category.

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 400 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" => "Daniel Hsu", "AB" => "Chao Hsu Lin",
             "AC" => "Jack Venberg", "AD" => "Sandy Yang",
             "AE" => "Ann Shan", "AF" => "Manchen Jin",
             "AG" => "Hudson Gilmore", "AH" => "Manny Munoz",
             "AI" => "Will Bigelow", "AJ" => "Zach Wu");
$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 (isset($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)