mtownsend
11/15/2018 - 7:29 PM

invalid_json

Determine if a json string is invalid.

<?php

if (!function_exists('invalid_json')) {

    /**
     * Determine if a json string is invalid.
     *
     * @param string $json
     * @return boolean
     * @author Mark Townsend <mtownsend5512@gmail.com>
     *
     */
    function invalid_json($json = null, $dump = false)
    {
        // Argument must be a string
        if (is_string($json)) {
            // If true is passed for the second argument, kill the script and dump the contents of the supplied JSON string
            if ($dump == true) {
                debug($json); // Requires custom function: debug()
            }

            $validation = json_decode($json, true);

            // If there is a json error or the string is null after being decoded, it's invalid
            if (json_last_error() != 'JSON_ERROR_NONE' || $validation === null) {
                return true;
            } // No JSON error or null value, it's valid
            else {
                return false;
            }
        } else {
            return true;
        }
    }
}