A safe way to get an alphanumeric string from user input? (without preg_replace)

I read many other questions regarding how to filter a string in "Alpha-numeric", but they all offer a method preg_replace().

According to OWASP :

The preg_replace () function should not be used with an unsanitised user input, because the payload will be eval () ed13.

preg_replace ("/.*/e", "system (echo / etc / passwd)");

Reflection could also have the disadvantages of code injection. See Relevant Documentation, as this is an advanced topic.

So how do I achieve this without preg_replace?

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $_POST['data']);
// Notice the $_POST['data']
+4
source share
4 answers

preg_replace() . OWASP , .

, - - . , .

+5
  • , OWASP , , .
  • , , PHP. .
  • , , .

:

$result = ctype_alnum($_POST['data']) ? $_POST['data'] : null;
+2

- :

<?php
$unsafe_input = 'some"""\'t&%^$@!`hing~~ unsafe \':[]435^%$^%*$^#'; // input from user

$safe_input = ''; // final sanitized string

// we want to allow 0-9 A-Z and a-z
// merge and flip so that we can use isset() later
$allowed_chars = array_flip(array_merge(range(0, 9), range('A', 'Z'), range('a', 'z')));

// loop each byte of the string
for($i = 0; $i < strlen($unsafe_input); ++$i)
{
    // isset() is lightyears faster than in_array()
    if(isset($allowed_chars[$unsafe_input[$i]]))
    {
        // good, sanitized, data
        $safe_input.= $unsafe_input[$i];
    }
}

echo $safe_input;
+1

, , :

if ( ! preg_match('/^[a-z0-9:_\/|-]+$/i', $str))
{

//do your stuff
}
+1

Source: https://habr.com/ru/post/1660544/


All Articles