Web Programming Step by Step

Lecture 21
Web 2.0 and Web Services

Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.

Valid XHTML 1.1 Valid CSS!

What is "Web 2.0"?

web 2.0

What is a web service?

web service: software functionality that can be invoked through the internet using common protocols

Content ("MIME") types (1.2.3)

MIME type related file extension
text/plain.txt
text/html.html, .htm, ...
text/css.css
text/javascript.js
text/xml.xml
image/gif.gif
image/jpeg.jpg, .jpeg
video/quicktime.mov
application/octet-stream.exe

Setting content type with header

header("Content-type: type/subtype");
header("Content-type: text/plain");
print("This output will appear as plain text now!\n");

Example: Exponent web service

The $_SERVER superglobal array

index description example
$_SERVER["SERVER_NAME"] name of this web server "webster.cs.washington.edu"
$_SERVER["SERVER_ADDR"] IP address of web server "128.208.179.154"
$_SERVER["REMOTE_HOST"] user's domain name "hsd1.wa.comcast.net"
$_SERVER["REMOTE_ADDR"] user's IP address "57.170.55.93"
$_SERVER["HTTP_USER_AGENT"] user's web browser "Mozilla/5.0 (Windows; ..."
$_SERVER["HTTP_REFERER"] where user was before this page "http://www.google.com/"
$_SERVER["REQUEST_METHOD"] HTTP method used to contact server "GET" or "POST"

Emitting partial-page HTML data

# suppose my web service accepts a "type" query parameter ...
<?php if ($_REQUEST["type"] == "html") { ?>
	<ul>
		<?php foreach ($students as $kid) { ?>
			<li> <?= $kid ?> </li>
		<?php } ?>
	</ul>
<?php } ?>

Emitting XML data

...
header("Content-type: text/xml");
print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
?><books>
<?php foreach ($books as $title) { ?>
	<book title="<?= $title ?>" />
<?php } ?>
</books>

Reporting errors

Using headers for HTTP error codes

header("HTTP/1.1  code  description");
if ($_REQUEST["foo"] != "bar") {
	# I am not happy with the value of foo; this is an error
	header("HTTP/1.1 400 Invalid Request");
	die("An HTTP error 400 (invalid request) occurred.");
}
if (!file_exists($input_file_path)) {
	header("HTTP/1.1 404 File Not Found");
	die("HTTP error 404 occurred: File not found ($input_file_path)");
}

Checking for mandatory query parameters

function require_params($params) {
	# allow calling as a varargs function
	$params = func_get_args();
	foreach ($params as $param) {
		if (!isset($_REQUEST[$param])) {
			header("HTTP/1.1 400 Invalid Request");
			die("HTTP/1.1 400 Invalid Request: missing required parameter $param");
		}
	}
}