Location: PHPKode > scripts > PHP Shoutbox > php_shoutbox/index.php
<?php
/*
** Shoutbox
** Mainly just uses the Post class from post.php.  Also uses header.txt and 
** footer.txt.
** 
*/

require ('settings.php');
require ('post.php');

$output = ''; // output - this will contain the HTML, etc sent to the browser

// DATABASE INFORMATION
try
{
	$db = new PDO(DB_SOURCE, DB_USER, DB_PASS);
}
catch (Exception $exc)
{
	die('Database error, likely file not found or a permissions problem.');
}

// MAIN SCRIPT

// insert header
$output .= file_get_contents('header.txt');

if (!isset($_POST['submit']))
{
	// display input form
	$output .= '<form action="index.php" method="POST">

Name<br>
<input type="text" name="name" size="20" maxlength="' 
. Post::$max_name_length . '"><br>
<br>
Message<br>
<input type="text" name="message" size="20" maxlength="' 
. Post::$max_message_length . '"><br>
<br>
' . htmlentities(QUESTION, ENT_QUOTES) . '<br>
<input type="text" name="answer" size="7">
<small>No punctuation or spaces, case insensitive.</small><br>
<br>
<input type="submit" value="Submit" name="submit">
</form>';

	// display posts
	$posts = Post::get_posts($db);

	if ($posts === false)
	{
		die('Unable to get posts');
	}

	if (!isset($posts[0]))
	{
		// no entries returned
		$output .= '<p>No entries yet!</p>
				<div class="line"></div>';
	}
	else
	{
		for($i = 0; $i < count($posts); $i++)
		{
			$name = $posts[$i]->get_name();
			$message = $posts[$i]->get_message();

			$output .= "<p><b>$name:</b> $message</p><div class=\"line\"></div>";
		}
	}
}
else
{
	// input check for required fields
	if (!isset($_POST['name']) ||
		!isset($_POST['message']) ||
		!isset($_POST['answer']) ||
		strtolower($_POST['answer']) != strtolower(ANSWER))
	{
		die('Error: name, message and valid answer are required. <a href="index.php">Return</a>.');
	}

	// try to insert
	$post = new Post($db);

	if (!$post->set_name($_POST['name']) ||
		!$post->set_message($_POST['message']) ||
		!$post->set_ip($_SERVER['REMOTE_ADDR']) ||
		!$post->set_date(time()))
	{
		die('Invalid input: ' . $post->get_error());
	}

	if ($post->save($db))
	{
		$output .= '<p>Post saved. <a href="index.php">Return</a>.</p>';

		// prune older posts
		Post::prune($db, POSTS_TO_KEEP);
	}
	else
	{
		$output .= '<p>Post could not be saved, either you already posted very recently or 
					there was a problem with the database.  Try waiting ' 
					. Post::$post_threshhold . ' seconds';
	}
}

// insert footer and output the HTML, etc
$output .= file_get_contents('footer.txt');
echo $output;
?>
Return current item: PHP Shoutbox