PHP Web Services

CSE 190 M (Web Programming) Spring 2008

University of Washington

Except where otherwise noted, the contents of this presentation are © Copyright 2008 Marty Stepp and Jessica Miller and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.1 Valid CSS!

Lecture outline

What is a web service?

web service: a software system exposing useful functionality that can be invoked through the internet using common protocols

Arrays

Creating an array

$name = array();                         # create
$name = array(value0, value1, ..., valueN);

$name[index]                              # get element value
$name[index] = value;                      # set element value
$name[] = value;                          # append
$a = array();     # empty array (length 0)
$a[0] = 23;       # stores 23 at index 0 (length 1)
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!";   # add string to end (at index 5)

Array functions

Array function example

$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
	$tas[$i] = strtolower($tas[$i]);
}                                 # ("md", "bh", "kk", "hm", "jp")
$morgan = array_shift($tas);      # ("bh", "kk", "hm", "jp")
array_pop($tas);                  # ("bh", "kk", "hm")
array_push($tas, "ms");           # ("bh", "kk", "hm", "ms")
array_reverse($tas);              # ("ms", "hm", "kk", "bh")
sort($tas);                       # ("bh", "hm", "kk", "ms")
$best = array_slice($tas, 1, 2);  # ("hm", "kk")

foreach loop

foreach ($array as $variableName) {
	...
}
$stooges = array("Larry", "Moe", "Curly", "Shemp");
for ($i = 0; $i < count($stooges); $i++) {
	print "Moe slaps {$stooges[$i]}\n";
}
foreach ($stooges as $stooge) {
	print "Moe slaps $stooge\n";  # even himself!
}

Splitting/joining strings

$array = explode(delimiter, string);
$string = implode(delimiter, array);
$s  = "CSE 190 M";
$a  = explode(" ", $s);     # ("CSE", "190", "M")
$s2 = implode("...", $a);   # "CSE...190...M"

Unpacking an array: list

list($var1, ..., $varN) = array;
$line = "stepp:17:m:94";
list($username, $age, $gender, $iq) = explode(":", $line);

Non-consecutive arrays

$autobots = array("Optimus", "Bumblebee", "Grimlock");
$autobots[100] = "Hotrod";

Associative arrays

$blackbook = array();
$blackbook["marty"] = "206-685-2181";
$blackbook["stuart"] = "206-685-9138";
...
print "Marty's number is " . $blackbook["marty"] . ".\n";

Creating an associative array

$name = array();
$name["key"] = value;
...
$name["key"] = value;
$name = array(key => value, ..., key => value);
$blackbook = array("marty" => "206-685-2181",
                   "stuart" => "206-685-9138",
                   "jenny" => "206-867-5309");

Printing an associative array

print_r($blackbook);
Array
(
    [jenny] => 206-867-5309
    [stuart] => 206-685-9138
    [marty] => 206-685-2181
)

foreach loop and associative arrays

foreach ($blackbook as $key => $value) {
	print "$key's phone number is $value\n";
}
jenny's phone number is 206-867-5309
stuart's phone number is 206-685-9138
marty's phone number is 206-685-2181

Associative array functions

# if (!isset($blackbook["marty"]))
if (!array_key_exists("marty", $blackbook)) {
	print "No phone number found for Marty Stepp.\n";
}

Query parameters

Scripts that accept query string parameters from their web requests

The main idea

https://example.com/student_login.php?username=stepp&sid=1234567

Query parameters: $_REQUEST

$user_name = $_REQUEST["username"];
$student_id = (int) $_REQUEST["sid"];

Example: Exponent web service

header("Content-type: text/plain");

$base = $_REQUEST["base"];
$exp = $_REQUEST["exponent"];
$result = pow($base, $exp);

print "$base ^ $exp = $result\n";

http://example.com/exponent.php?base=3&exponent=4

3 ^ 4 = 81

Example: Print-all-parameters web service

header("Content-type: text/plain");

foreach ($_REQUEST as $param => $value) {
	print "Parameter $param has value $value\n";
}

http://example.com/print_params.php?name=Marty+Stepp&sid=1234567

Parameter name has value Marty Stepp
Parameter sid has value 1234567

Checking for a parameter's existence

if (isset($_REQUEST["creditcard"])) {
	$cc = $_REQUEST["creditcard"];
	...
} else {
	print "You did not submit a credit card number.\n";
	...
	return;
}

GET or POST?

if ($_SERVER["REQUEST_METHOD"] == "GET") {
	# process a GET request
	...
} elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
	# process a POST request
	...
}

URL-encoding

File I/O

Interacting with files and directories in PHP

PHP file I/O functions

Reading/writing files

$text = file_get_contents("schedule.txt");
$lines = explode("\n", $text);
$lines = array_reverse($lines);
$text = implode("\n", $lines);
file_put_contents("schedule.txt", $text);

Reading files example

# Returns how many lines in this file are empty or just spaces.
function count_blank_lines($file_name) {
	$text = file_get_contents($file_name);
	$lines = explode("\n", $text);
	$count = 0;
	foreach ($lines as $line) {
		if (strlen(trim($line)) == 0) {
			$count++;
		}
	}
	return $count;
}
...
print count_blank_lines("lecture18-php_web_services.html");

Reading directories

$folder = "images";
$files = scandir($folder);
foreach ($files as $file) {
	if ($file != "." && $file != "..") {
		print "I found an image: $folder/$file\n";
	}
}

Headers

header("Content-type: text/plain");