Web Programming Step by Step

Lecture 22
Web 2.0 and Web Services

Except where otherwise noted, the contents of this presentation are Copyright 2009 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

Recall: HTTP GET vs. POST (6.3.3)

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"

GET or POST?

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

Emitting partial-page HTML data

# suppose my web service accepts a "type" query parameter ...
if ($_REQUEST["type"] == "html") {
	# client wants their output to be HTML format
	?>
	<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");
print("<books>\n");
foreach ($books as $title) {
	print("<book title=\"$title\" />\n");
}
print("</books>\n");

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)");
}