Skip to content

Instantly share code, notes, and snippets.

@lornajane
Created August 9, 2013 08:13
Show Gist options
  • Save lornajane/6191971 to your computer and use it in GitHub Desktop.
Save lornajane/6191971 to your computer and use it in GitHub Desktop.
Toy Messages classes
<?php
class Message
{
public function __construct($msg, $user) {
$this->msg = $msg;
$this->user = $user;
$this->created = new DateTime();
}
public function getAsHtml() {
$html = "<li>" . $this->user . " said: ";
$html .= "<em>" . $this->msg . "</em>";
$datetime = $this->created;
$html .= " on " . $datetime->format('F jS');
$html .= "</li>";
return $html;
}
}
<?php
session_start();
require('Message.php');
?>
<h1>Messages</h1>
<a href="new_message.php">New message</a>
<?php
if($_SESSION['messages'] && is_array($_SESSION['messages'])) {
echo "<ul>";
foreach($_SESSION['messages'] as $msg) {
$data = unserialize($msg);
echo $data->getAsHtml();
}
}
<?php
session_start();
require('Message.php');
if($_POST) {
$user = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);
$msg = filter_input(INPUT_POST, "message", FILTER_SANITIZE_STRING);
if(!empty($msg)) {
$message = new Message($msg, $user);
$_SESSION['messages'][] = serialize($message);
header("Location: messages.php");
} else {
echo "Try again";
}
}
?>
<h1>New Message</h1>
<form method="post">
Name: <input type="text" name="name" />
Message: <textarea name="message"></textarea>
<input type="submit" value="save" />
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment