Search code examples
phpjsonsanitize

How to sanitize a stdClass in PHP


I need to sanitize the values in a JSON file (e.g., a composer.json file from github). I json_decode($file) converting it to a stdClass object. (I need it as an object, not as an array - I am aware of that option).

I need to recursively sanitize all the values which might be objects as well (and maybe the keys too?).

I need to remove any and all "dangerous" characters, etc from the file but would like it to remain multilingual, so was planning to use filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW).

Advice and suggestions please. maybe I'm missing the obvious, but this seems harder than it should.


Solution

  • Answer by Михаил-М was close. I needed to adjust it slightly to be:

    function sanitize($data) {
        foreach ($data as &$value) {
            if (is_scalar($value)) {
                $value = sanitizeValue($value);
                continue;
            }
    
            $value = sanitize($value);
        }
    
        return $data;
    }
    

    of course, this doesn't address the issue of actually sanitizing the data which I did with the filter_var method I mentioned above. so I finally solved it with this:

    function sanitize($data) {
        foreach ($data as &$value) {
            if (is_scalar($value)) {
                $value = filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
                continue;
            }
    
            $value = sanitize($value);
        }
    
        return $data;
    }