1

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?

10
  • Use if (!strpos("["))
    – Mohammad
    Oct 8, 2018 at 7:45
  • @Mohammad Sorry, can you give me an example?
    – Jackie
    Oct 8, 2018 at 7:47
  • Welcome. www.example.com/myfile.php?input=John1 contains non-alphanumeric characters.
    – brombeer
    Oct 8, 2018 at 7:48
  • Something like 3v4l.org/FWWY5
    – Mohammad
    Oct 8, 2018 at 7:50
  • if (is_string($_GET['input'])) {echo 'variable is a string';} Oct 8, 2018 at 7:53

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.