PHP str_word_count’s and validating base64 strings…

  • PHP

Recently I had to validate a string that is was indeed a base64 string and it was indeed an encoded allowable image type. Between str_word_count’s second parameter (returning the string as an array based on the words) and a quick Stack Overflow search this is neat little piece of logic IMO:

/**
 * Validate a base64 string is indeed of an allowable MIME type
 * @author David J Eddy <me@davidjeddy.com>>
 * @version 0.8.0
 * @param $paramData
 *
 * @return bool
 */
public function validate($paramData)
{
    $returnData = true;
    // explode the string into an array ignoring everything but words
    $wordArray = str_word_count(substr($paramData, 0 , 23), 1);

    // is the string a valid base64 object?
    // @source http://stackoverflow.com/questions/4278106/how-to-check-if-a-string-is-base64-valid-in-php
    if (base64_encode(base64_decode($paramData, true)) !== $paramData) {
        $returnData = false;
    }

    // does the string contain 'data', 'image', 'base'?
    if (
        in_array('data', $wordArray) === false ||
        in_array('image', $wordArray) === false ||
        in_array('base', $wordArray) === false ||
        $returnData === false
    ) {
        $returnData = false;
    }

    // does the string contain an allowed MIME type?
    if (in_array('data', $this->allowableMimeType) === false || $returnData === false) {
        $returnData = false;
    }

    return $returnData;
}

What do you think? Have an often forgotten php function or parameter that helps you greatly?

Leave a Reply

Your email address will not be published. Required fields are marked *