WordPress has the unfortunate legacy situation of having to force input variables to be “magic quoted”, something which has been deprecated in PHP for some time. So when you are working with data passed from the user, you have to run those input variables ($_GET
, $_POST
, $_REQUEST
) through stripslashes()
, which is really annoying. At least I\’m annoyed by it.
However, I just made a discovery. As of 5.2, PHP comes with an extension for Data Filtering, including a function filter_input
function for fetching input variables and passing them through validation, sanitization, and other filters.
Well, it turns out that when you access input variables through filter_input
, it bypasses wp_magic_quotes
entirely, and so you’ll get raw un-backslashed data back! So instead of accessing $_GET['x']
, you call filter_input( INPUT_GET, 'x' )
.
Additionally, using filter_input()
has the benefit of not having to add isset()
and !empty()
checks everywhere that you’re interacting with input variables, so as to avoid the plague of PHP notices about undefined array indexes. (Oh, hello most WordPress plugins in existence!)
And the icing on the cake for filter_input
is that you get validation and sanitization.
However, there’s one big caveat about all this. The WordPress API functions like update_post_meta()
and friends actually expect the input to be magic-quoted. So if you do this:
update_post_meta( get_the_ID(), 'x', 'I love \o/ WordPress!' );
If you grab that postmeta out:
$x = get_post_meta( get_the_ID(), 'x', true );
Then $x
will end up being:
I love o/ WordPress!
Nooooooooooooooooooooooooooo.
For more info, see #18322: The Road to Magic Quotes Sanity.
One reply on “Revelations about filter_input”
Hi Weston,
Thanks for your post. It’s old but still useful for me this time. It’s important to know that the data get via filter_input is not affected by any method that tries to change the value, including wp_magic_quotes(). It took me hours to found that!