18 Apr 2025

You Don’t Need to Sanitize User Input Before Casting as an Integer in a WordPress Plugin

A basic rule of security is to not trust user input. Many vulnerabilities exist because software developers assume that only legitimate and valid data will be submitted to the software. So the developers of WordPress plugins should do some combination of sanitization, validation, and escaping with user input. Developers can overdue on those things. We ran across an example while working on a security review of a plugin chosen by our customers.

Here is the relevant code in the plugin (plenty of other plugins, it turns out, have similar code):

$getterId = (int)sanitize_text_field( wp_unslash( $_GET['preview_id'] ) );

That code takes user input that should only be an integer and passes it through two WordPress functions and then casts it as an integer.

As the value should only be an integer, there is no need to pass it through wp_unslash(). As that removes slashes added to certain characters by add_slashes() and none of those characters are integers.

After doing that unslashing, the code sanitizes the value using sanitize_text_field(). That isn’t necessary as casting the value as an integer will sanitize the value even more stringently than sanitize_text_field(). As the value can only contain integers.

So all you really need to do there is to cast it as an integer. You might then want to validate that the variable contains an expected integer value, but you would want to do that with the other code as well.


Need Help Fixing a Vulnerability in Your Plugin?

We are happy to help you get it fixed for free, since warning the customers of our service about vulnerabilities in their plugins isn't very useful if there isn't a fixed version available.

Leave a Reply

Your email address will not be published.