How to protect against input arrays

2019-08-01 19:16发布

问题:

I have a program. It accepts an input of a alphanumeric string (which I already do checks for). So a valid input would be www.example.com/myfile.php?input=John1

However, if someone were to type in www.example.com/myfile.php?input[] then it breaks my entire program's logic breaks because I don't accept input as an array. How can I unsure the thing a user enters is just a string. Not an array, or any other data types/structures?

回答1:

There is the slow and tedious way of solving this problem, which involves a lot of manual type-checking. Expect to wear your keyboard out writing if (!is_string($foo)) conditions throughout your application.

Or you could use Ionizer which was designed for solving this exact problem.

<?php

use ParagonIE\Ionizer\GeneralFilterContainer;
use ParagonIE\Ionizer\Filter\{
    StringFilter,
    WhiteList
};

// Define properties to filter:
$ic = new GeneralFilterContainer();
$ic->addFilter(
        'username',
        (new StringFilter())->setPattern('^[A-Za-z0-9_\-]{3,24}$')
    )
    ->addFilter('passphrase', new StringFilter())
    ->addFilter(
        'domain',
        new WhiteList('US-1', 'US-2', 'EU-1', 'EU-2')
    );

// Invoke the filter container on the array to get the filtered result:
try {
    // $post passed all of our filters.
    $post = $ic($_POST);
} catch (\TypeError $ex) {
    // Invalid data provided.
}

If someone attempts to pass an array instead of a string, $ic($_POST) throws a TypeError which you can then catch, log, and fail gracefully.



标签: php security get