How and when to use filter_xss() and check_plain()? There are lots of template files like this one views-view-fields--magazine--magazine.tpl.php in my website. how and when I should use the filter_xss()  and check_plain() to improve security? for example this is the code:

&lt;div&gt;
    &lt;div class="bf-header bf-article-header"&gt;&lt;?php print $fields['title']-&gt;content; ?&gt;&lt;/div&gt;
    &lt;div class="bf-article-body"&gt;&lt;?php print $fields['field_magazine_body']-&gt;content;?&gt;&lt;/div&gt;
    &lt;div class="bf-article-image"&gt;&lt;?php print $fields['field_magazine_image']-&gt;content;?&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="separator article-view-separator"&gt;&lt;/div&gt;


How do I can apply those functions in it?
First, read up about these in the Drupal API:


filter_xss
check_plain


So check_plain() encodes special characters that has special meaning in HTML (such as &lt; and &amp;) into plain text entities (i.e. &amp;lt; and &amp;amp; respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup. The function filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. It does four things:


Removing characters and constructs that can trick browsers
Making sure all HTML entities are well-formed
Making sure all HTML tags and attributes are well-formed
Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)


Both functions are used to sanitize data from users to make sure that any user injection is neutralized before the data is rendered on your site.  

You never pass the same string through both.

If you use check_plain() then the string passed to the function is supposed to be used as plain text (not HTML). Then filter_xss() is not needed, since check_plain() will always make the string plain text.

If you use filter_xss(), then the string passed to the function is supposed to be HTML, and check_plain() will mess it up.

When I look at the template you use as example, it looks to me as if all three fields passed to print() comes from content that is already sanitized, and need no more sanitation.

However, if you create your own module that collects user input without passing it through a "safe" text filter such as "Filtered HTML" or "Plain", you must use these functions for sanitation purposes.