skip to Main Content

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


  1. Add below code in your function.php file this will disallow the script injection inside the search form.

    add_filter( 'posts_search', 't5_search_escaped_characters', 10, 2 );
    
    function t5_search_escaped_characters( $search, $obj = NULL )
    {
        if ( $obj->is_search and empty ( $search ) and is_main_query() )
        {
            remove_filter( current_filter(), __FUNCTION__ );
            return ' AND 1 = 2 ';
        }
        $s   = $obj->query_vars['s'];
        // Double-encoding FALSE in case another plugin did that already.
        $esc = htmlspecialchars( $s, ENT_NOQUOTES, 'utf-8', FALSE );
        return str_replace( "%$s%", "%$esc%", $search ) . ' ';
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search