Search code examples
phpfilejoomlastrpos

Joomla PHP using a text file to blacklist words


So i have a text document in my joomla root path called banned.txt contents look like the following (on new lines):

fuck
fucking
etc

Now the way i have already solved this is with the following code. But rather than have a big list of arrays in my php code i would rather just somehow pull the banned words from the text document in my public_html folder.

$mtitle = $file['name'];
$find = array('fuck', 'fucking', 'etc');
foreach ($find as $n) {
    if(strpos($mtitle,$n) !== false) {
        $this->setError(JText::_('Banned word detected'));
        return false;
    }
}

Any help in order to pull out c:/website/public_html/banned.txt and check that file to see if any of the words match would be great :)


Solution

  • Wouldn't file be suitable for your purposes? As we can read in PHP documentation:

    file — Reads entire file into an array

    So using file your code would look like this:

    $mtitle = $file['name'];
    $find = file("c:/website/public_html/banned.txt",FILE_IGNORE_NEW_LINES);
    foreach ($find as $n) {
        if(strpos($mtitle,$n) !== false) {
            $this->setError(JText::_('Banned word detected'));
            return false;
        }
    }
    

    Please note, that only line with defining $find has changed, as file is returning array.

    EDIT:

    It appears that file is splitting file with newlines still attached. To ignore them you must use FILE_IGNORE_NEW_LINES as second parameter. I've updated code to contain it.

    Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.