I have a HTML form which essentially searches for posts in WordPress. The markup looks like this:
<form class="resourceFilters__searchForm position-relative" role="search" action="<?php echo site_url('/search/'); ?>" method="get">
<input class="resourceFilters__searchForm-input" type="text" name="keyword" placeholder="Search" />
<input class="resourceFilters__searchForm-btn" type="image" src="<?php echo get_template_directory_uri()." /assets/build/vectors/search-icon-bold.svg "; ?>" alt="Submit">
<input type="hidden" name="p_type" value="Resources" />
</form>
In this textfield, I ran a test and tried to search <script>alert(1);</script>
which executed on search – not ideal.
To prevent scripts
from being processed in this textfield, I tried the following:
add_action( 'pre_get_posts', 'intercept_banned_keywords' );
function intercept_banned_keywords ($query) {
$banned = array ('<script>', 'alert');
if ( in_array ($query->query_vars['s'], $banned) ){
$query->s = '';
}
}
But no luck. scripts
are still parsable in the textfield.
How can I prevent scripts from being allowed / searched in a field?
2
Answers
Add below code in your function.php file this will disallow the script injection inside the search form.
When you submit a form you need to sanitize the data.
use
sanitize_text_fiedl()
for text field values.More details on sanitization: https://developer.wordpress.org/apis/security/sanitizing/
After the form submissions it goes to siteurl/search. Find out the template used for that page (possibly search.php) and add your sanitization in the code.