A simple, no-dependency PHP library for defense against MongoDB query selector injection attacks. Inspired by the homonymous NPM package for NodeJS.
The library is available via Composer.
composer require aldin-sxr/mongo-sanitize
After installing, include vendor/autoload.php
in your project.
<?php
require_once 'vendor/autoload.php';
$data = [
'hello' => 'world',
'foo' => [ '$eq' => 'bar' ]
];
$cleaned = mongo_sanitize($data);
// Cleaned array:
// [ 'hello' => 'world, 'foo' => [ ] ]
Call mongo_sanitize()
on the arrays (user input) which you want to sanitize. The function will remove any array elements whose keys start with a $
(MongoDB operator identifier). The function also works recursively, on embedded array elements.
All library methods come with several unit tests in PHPUnit, which are available under tests/unit
.
The library is licensed under the MIT license. See the LICENSE file for details.