阻止HTML表单中的脚本注入



我有一个HTML表单,它本质上是在WordPress中搜索帖子。标记如下:

<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>

在这个文本字段中,我运行了一个测试,并尝试搜索在搜索时执行的<script>alert(1);</script>——这并不理想。

为了防止在此文本字段中处理scripts,我尝试了以下操作:

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 = '';
}
}

但运气不好。scripts在文本字段中仍然是可解析的。

如何防止在字段中允许/搜索脚本?

提交表单时,需要对数据进行清理。对文本字段值使用sanitize_text_fiedl()

有关消毒的更多详细信息:https://developer.wordpress.org/apis/security/sanitizing/

提交表单后,它会转到siteurl/search。找出用于该页面的模板(可能是search.php),并在代码中添加您的净化。

在function.php文件中添加以下代码,这将禁止在搜索表单中注入脚本。

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 ) . ' ';
}

最新更新