0

It doesn't happen outside of WordPress, so I'm posting here.

I'm using a textarea field in a custom form, and before I have a chance to do anything with it, I find it's escaped:

echo $_POST['my_textarea_field'];

gives: Let\'s do something with this!

(BTW: No, I won't echo a POST field outside of a sandbox)

This is PHP 7.1, so there won't be magic_quotes, or safe_mode to worry about.

Tried after switching back to twentyseventeen, and with all plugins disabled.

This should be basic functionality, but it has me puzzled.

1 Answer 1

3

WordPress always adds magic quotes regardless of server settings. This ensures consistency regardless of the environment. Even though magic quotes has been removed or deprecated from PHP, WordPress keeps this behaviour for backwards compatibility with older versions of PHP and plugins that were written with older versions of PHP in mind.

If you want to remove slashes you can use stripslashes() or stripslashesdeep():

$_POST = stripslashes_deep( $_POST );

Keep in mind that because of this behaviour parts of WordPress expect slashed data. See this quote from an announcement regarding the REST API:

We are regarding inconsistently-slashed data as a major bug, and are changing the API infrastructure to ensure unslashed data. This will ensure that data is consistent regardless of the source. Callbacks will now receive unslashed data only, and can rely on this regardless of the original data source or request method.

If you are using functions that expect slashed data in your callback, you will need to slash your data before passing into these functions. Commonly used functions that expect slashed data are wp_insert_post, wp_update_post, update_post_meta, wp_insert_term, wp_insert_user, along with others. Before passing data into these functions, you must call wp_slash() on your data.

While that's regarding the REST API, if you change the behaviour of the slashing in your own code, you could run into the same issues.

2
  • Thanks for the informative answer. I was completely unaware of this behavior until now. I would then suggest if you do a stripslashes_deep() on the entire $_POST array, assign it to a different variable, instead of back to $_POST.
    – De Coder
    Commented Aug 7, 2018 at 16:13
  • I upvoted the informative answer, but agree with @DeCoder that one shouldn't override the values in the global @_POST. I guess that wasn't the point with this answer either. Just a word of caution to the "copy-paste" developers.
    – jgangso
    Commented Sep 3, 2021 at 8:39

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.