ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.


Blacklist that spam, with PHP!

(Page 2 out of 2)

Creating our blacklist system is very. The first thing that must be done is open the blacklist. This is easily done using the file() function.

// Open blacklist file
$blacklist = file("/home/you/public_html/blacklist.txt");

The blacklist is now loaded in an array called blacklist. Each entry is a separate array item. All that�s left to do is loop through each entry, using foreach(), then checking if the entry isn�t a comment or blank, and finally checking the message for that entry, using preg_match() (after all, we did want regular expression support). The code looks something like this:

// Loop through blacklist, and check message
foreach ($blacklist as $item) {
        // Check if item isn't empty or comment
        $item = trim($item);

        if (!empty($item) AND substr($item, 0, 1) != "#") {
                // Not a comment, or empty, check message
                if (preg_match("/" . $item . "/i", $message, $match)) {
                        // Blacklisted URL found
                        die("Sorry, your message has been denied because a blacklisted URL (" . $match['0'] . ") has been found.");

That�s all there is to it. You can certainly make it a bit better by changing the error message, checking other fields (e.g. a separate �homepage� field), and even including relevancy points. But the above code will already stop a hell of a lot spam, if you�ve got a decent blacklist.

View sample script | Download sample script

« Previous: Introduction

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction
  2. The blacklist code
Bookmark Article
Download Article
Download this article as a PDF file