Search code examples
phpmysqlwordpresssql-injection

Does WordPress escape data to prevent SQL injections when using the Settings API?


I'm having a difficult time finding any information on this topic. I'm creating a plugin that allows users to add custom JS code such as, but not limited to, Google Analytics. To do this, I used the Settings API to create a settings page with a few textarea fields. I used the following page as a guide: https://developer.wordpress.org/plugins/settings/custom-settings-page/.

My question is, what do I need to do make sure the data going into the database is safe? Or is it already safe (i.e. escaped by WordPress)? I thought about using the sanitize_textarea_field function in a callback in the register_setting function, however, the data (e.g. <script src="example.com/script.js"></script) looks exactly the same with or without the sanitize function after it's serialized by WordPress.

Am I safe to assume that WordPress escapes all data going into the database if I use the Settings API, or do I need to write custom code to do this? If so, what is the process to escape data if I'm using the Settings API?


Solution

  • Yes, when you're using the WP API (not just for settings, but the other functions too, like update_post_meta, wp_insert_post etc), WP will make sure that data is properly escaped before it is sent to the database.

    The few exceptions will state explicitly that you can input SQL (e.g. the posts_orderby filter).

    Unless you have unsafe characters (single quotes!) in your data, you won't see a change before and after escaping. Note that the sanitize_* functions don't deal with SQL injections, but try to clean up the content.