Security Best Practices

Learn about security precautions while saving user generated content and reading data from the database.

Someone may come to the site and in the body field, instead of writing a note, they might write some JavaScript code like <script>alert("Hahaha")</script> to make an alert message pop up. Now an alert is not something malicious but the idea is that if we are able to execute any JavaScript code, that is a security gap. You can execute any malicious JavaScript too.

However, when we save this note, we see that the opening and closing tags are removed by WordPress which prevents this code from actually being executed as JS. By default, WordPress only allows admin accounts to post unfiltered HTML.

Posting unfiltered HTML

Back in the admin window, go to "Users" and open the subscriber role ("datajek"), in the "General" tab, there is a capability named unfiltered HTML which is unchecked. The ability to post unfiltered HTML that can contain JavaScript is a powerful capability, not even the editor and author roles have it. Only the administrator can ever post unfiltered HTML. But we have to take into account a situation in which the admin account gets hacked.

As an admin if we create a lecture post with title Hack test and paste some code in the content like <script>alert("Hahaha")</script>, we see that the post gets saved as it is without removing the <script> tags. The good news is that WordPress does not execute the script.

This is because of the escape functions we used. When fetching the content from the textarea, we used get_the_content() function and enclosed it in the esc_textarea() function. If we remove the escape function and only use get_the_content(), the JavaScript code will execute and the alert message is displayed.

Get hands-on with 1200+ tech skills courses.