$_POST field value gets altered after "init"

I'm new to wordpress development.

I'm trying to develop a simple plugin for practice. It involves a form submission from the frontend. The form has an input with the following code.

input type='hidden' name='test' value='{id: 1}'/

When I submit the form, the value of 'test' field gets altered after the init hook.

My plugin code looks like the following

add_action('init', [$this, 'init']);

function init() {
    printe_r($_POST);
}

Output:

Array
(
    [test] = {\id\:1}
)

The problem is that json_decode errors out. I have to use stripslashes like below to decode the json string.

json_decode(stripslashes($_POST['test']));

Is this behavior expected in Wordpress?

Topic input plugins Wordpress

Category Web


As @mozboz explained, WordPress is changing the values of $_POST, $_GET, $_REQUEST, and $_COOKIE. If you need the raw values, use the function filter_input(), and make sure to keep security concerns in mind.

Example:

$test = filter_input( INPUT_POST, 'test', FILTER_SANITIZE_STRING );

Yes, it's the expected behaviour. There's information on why it works like this here, and this function which can help in removing slashes from larger data structures: https://developer.wordpress.org/reference/functions/stripslashes_deep/

In the short term, if you can live without JSON for this field, why not just remove it, and if you need multiple hidden fields add them separately, e.g.:

<input type='hidden' name='testId' value='1'/>
<input type='hidden' name='otherId' value='123'/>

And you can get those directly with:

echo $_POST['testId'];
echo $_POST['otherId'];

Will output:

1
123

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.