PHP class for detecting and handling possible mail headers in text

Here's simple PHP class for detecting and handling possible mail headers in a string. It is useful for sanitizing input data from contact forms, guest books, etc. before sending it via email to prevent header injection. It has three main functions:

<?php

/**
 * Class for detecting possible mail headers in string. Can be used for verifying web form input before sending via
 * email.
 */
class MailHeadersHandler {

    /**
     * All posible headers according to RFC.
     * @var array
     */
    protected $mail_rfc_headers= array('Date', 'From', 'Sender', 'Reply\-To', 'To', 'Cc', 'Bcc', 'Message\-ID',
                'In\-Reply\-To', 'References', 'Subject', 'Comments', 'Keywords', 'Resent\-Date', 'Resent\-From',
                'Resent\-Sender', 'Resent\-To', 'Resent\-Cc', 'Resent\-Bcc', 'Resent\-Message\-ID', 'Return\-Path',
                'Received');

    /**
     * Detect all possible header patterns.
     * @param string string text that is searched.
     * @return array() false if no headers found, array of possible headers otherwise.
     */
    function detect($string) {
        $matches= array();

        foreach($this->mail_rfc_headers as $header) {
            $regex= '/'.$header.'\s*\:/i';
            if(preg_match($regex, $string, $arr)) {
                $matches[]= $arr[0];
            }
        }

        if(count($matches) == 0)
            return false;

        return $matches;
    }

    /**
     * Deletes all posible header patterns.
     * @param string string text that is searched.
     * @return string text with removed header patterns.
     */
    function erase($string) {
        foreach($this->mail_rfc_headers as $header) {
            $regex= '/'.$header.'\s*\:/i';
            $string= preg_replace($regex, '', $string);
        }
        return $string;
    }

    /**
     * Escapes header pattern to header_value format.
     * @param string string text that is searched.
     * @return string text with escaped header patterns.
     */
    function escape($string) {
        foreach($this->mail_rfc_headers as $header) {
            $regex= '/('.$header.')\s*\:/i';
            $string= preg_replace($regex, '\1_', $string);
        }
        return $string;
    }

}
?>

 

No comments yet

Back to articles list

This page was last modified on 2024-04-19 10:05:03