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.
Part I: Functions and Simple Arrays
Part II: PHP GET Web Services
Part III: Web Services with Associative Arrays (Precursor to JSON APIs!)
array_mystery
longest_string
switch_pairs
(challenge)(go down to work on these!)
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;
}
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).
[8]
:
[6, 3]
:
[1, 2, 3, 4]
:
[7, 10, 12, 12, 17]
:
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.
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
.
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}!";
isset
header
:
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!";
}
header
header
is a PHP function to set different information in the response
header. In our web services, we will use it to:
text/plain
)header
to Set the Output TypeRemember 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!";
}
This example shows the default Content-Type as text/html
This example shows the result of setting Content-Type as text/plain
and the plain text in the response
header
to Set Error Response CodesRemember 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!";
}
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)
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.
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.
One solution can be found here.
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";
A convenient way to loop over each element of an array without indices!
foreach ($array_name as $value) {
echo "Found value: {$value}\n";
}
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";
}
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!)
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])) {
...
}
When you're done, move on to Part 2 on the slide below.
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".
You can find a solution here (with example PHP documentation)