Exercise : Address Book (by Alex Miller)

You are given HTML and JS files for an address book web application. The javascript file sends requests to a web service that reads and saves address data. You can view the working application here. Write the PHP file, addressbook.php, that provides the following behavior:

Extra: Edit addressbook.js to add Scriptaculous effects to the page.

Exercise Address Book

header("Content-type: text/plain");
$file_text = file_get_contents("addresses.txt");
if ($_SERVER['REQUEST_METHOD'] == "GET") {
    $lines = explode("\n", $file_text);
    if (isset($_GET["name"])) {
        $name = $_REQUEST["name"];
        foreach ($lines as $line) {
            $info = explode(",", $line);
            if ($info[0] == $name) {
                print $info[1];
            }
        }
    } else {
        $names = array();
        foreach ($lines as $line) {
            $info = explode(",", $line);
            array_push($names, $info[0]);
        }
        print(implode($names, ","));
    }
} 

Exercise Address Book

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $name = $_REQUEST["name"];
    $address = $_REQUEST["address"];
    $file_text = file_get_contents("addresses.txt");
    $file_text .= "\n" . $name . "," . $address;
    file_put_contents("addresses.txt", $file_text);
}