|
CS479/579 - Web Programming II
| Displaying exercises/e5/solution/mboard.php
<?php
/**
* Loads and JSON decodes the messages file (as associative arrays in the case
* of JSON objects. This assumes that the messages file already exists and is
* already writable by the web server.
*/
$msgs = json_decode(file_get_contents("messages"), true);
// If the data we get is not of type array, we assume the file is either empty
// or corrupt and initialize $msgs to an empty array:
if (gettype($msgs) != "array") $msgs = array();
/**
* Handle the post data if any:
*/
if ($_POST['mesg']) {
$title = isset($_POST['title'])? htmlspecialchars($_POST['title']) : "";
$mesg = htmlspecialchars($_POST['mesg']);
// Creates a new message "object":
$m = array("title" => $title, "mesg" => $mesg);
// Appends it to the $msgs array:
array_push($msgs, $m);
// Writes back the messages file. (alternate way to write the data).
// file_put_contents("messages", json_encode($msgs))
$f = fopen("messages", "w");
fwrite($f, json_encode($msgs));
fclose($f);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title> Messages </title>
<style>
#m th { background: lightgray; font-size: 150%;}
#m td { border-bottom: 1px solid gray; }
</style>
</head>
<body>
<h1> Assignment #4 </h1>
<table id='m'>
<?php
/**
* Go through each message of the array and output it as a pair of table
* rows.
*/
if (count($msgs) > 0) {
foreach($msgs as $msg) {
$t = $msg['title'];
$m = $msg['mesg'];
echo "<tr><th>{$t}\n";
echo "<tr><td>{$m}\n";
}
} else {
echo "<tr><td> No messages\n";
}
?>
</table>
<br><br><hr>
Add message:
<form method='post'>
<table>
<tr><td>Title:<td><input type='text' name='title'>
<tr><td>Mesg:<td><textarea name='mesg'></textarea>
<tr><td colspan=2><input type='submit'>
</table>
</form>
</body>
</html>
|