<?

    // ensure complete form was submitted
    if (!isset($_POST["name"]) || !isset($_POST["item"]))
    {
        header("Location: http://www.cs75.net/lectures/4/src/lunch/lunch.php");
        exit;
    }

    // open XML file for reading + writing
    $handle = fopen("orders.xml", "r+");

    // acquire exclusive lock
    flock($handle, LOCK_EX);

    // read contents of XML file
    $contents = fread($handle, filesize("orders.xml"));

    // build DOM out of contents
    $xml = new SimpleXMLElement($contents);

    // add order
    $order = $xml->addChild("order");
    $order->addChild("name", $_POST["name"]);
    $order->addChild("item", $_POST["item"]);

    // overwrite original XML file
    rewind($handle);
    fwrite($handle, $xml->asXML());
    fclose($handle);
?>

<!DOCTYPE html PUBLIC
     "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Lunch</title>
  </head>
  <body>
    One <?= $_POST["item"] ?> for <?= $_POST["name"] ?>, coming right up!
  </body>
</html>
