How to protect against input arrays

白昼怎懂夜的黑 提交于 2019-12-24 08:08:13

问题


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.



来源:https://stackoverflow.com/questions/52697587/how-to-protect-against-input-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!