Build Your Own DatabaseDriven Website Using PHP amp;amp; MySQL [Electronic resources]

Kevin Yank

نسخه متنی -صفحه : 190/ 61
نمايش فراداده

Out with the Old

Before we introduce a new method to format text, we should first disable the old one. A user with no knowledge of HTML might unknowingly include HTML syntax (however invalid) in a plain text document, and if this syntax is still accepted, it could produce unexpected results—or even mess up your finely tuned page layout. Consider the following sentence:

The gunman drew his weapon. <BANG!>

The user who entered this text into the database might be surprised to see the last word (<BANG!>) missing from the Web page that displayed this content. And while anyone with a basic knowledge of HTML would know that the Web browser discarded that segment of text as an invalid HTML tag, we're trying to cater to users with no knowledge of HTML whatsoever.

In "A Content Management System", we saw a PHP function that solved this problem quite neatly: . This function, when applied to the text of our joke before it was inserted into a Web page, would convert the string above into the following "HTML safe" version:

The gunman drew his weapon. &lt;BANG!&gt;

When this string was interpreted by the site visitor's Web browser, it would produce the desired result. As a first step, therefore, we must modify the PHP file on our Website that displays the text of jokes, so that it uses on all text before it outputs it to the Web. Since up until now I have not given the complete code for a page to display a joke, I'll be starting from scratch. The complete code for joke.php with this entire chapter taken into account is provided in the code archive, so don't feel that you have to follow along by typing out the code that I'll show you.

Here's the basic code for fetching a joke with a given ID out of the database and formatting it for display by converting it to an “HTML Safe” version:

<!-- joke.php -->
...
// Get the joke text from the database
$id = $_GET['id'];
$joke = mysql_query("SELECT JokeText FROM Jokes
WHERE ID=$id");
$joke = mysql_fetch_array($joke);
$joketext = $joke['JokeText'];
// Filter out HTML code
$joketext =lspecialchars($joketext);
echo( $joketext );
...

We have now neutralized any HTML code that may appear in the site's content. With this clean slate, we are ready to implement a markup language of our own that will let administrators format content.