Let us take an example of a simple application like Blog, where user can submit the comments after reading the article, which are being displayed. If the user is good and behaves nicely and enters only plain text, then it has no problem. Let’s imagine if the user submit the data
<b><i>This is a sample comment!!!!</i></b>
What will happen? The situation gets complicated. Browsers are not going to tell the difference between HTML tags which are displaying from Blog, it will be embedded in the comments.
It is still good if the user close the HTML tags, like in above code. All the HTML codes are closed properly. Imagine the situation if it not properly closed. Now the situation will be getting extreme bad, it will cause the browser to prevent page being displayed correctly. Like if someone submits
<b> or </b>
The situation will be worse if it contains Java Script. Then you will feel the power of Javascript, a malicious hacker can steal your cookies to his inbox, can redirect your pages to another web page, can steal your password which are saved in the browser. A lot of thing can be done by Javascript.
These kinds of problem are called XSS (Cross Site Scripting) attack.
If you want to remain safe from XSS then you need to code nicely as well as intelligently then you need to never display the direct input from the user. You need to remove the HTML tags first before displaying in the site.
But you will feel good to know, Php gives you two functions to remove the HTML tags or encode the special characters.
1. strip_tags() : It will removes the HTML tags from the string
2. htmlentities() : It will encode the special HTML characters.
Let’s see the how to use those functions:
//Remove the HTML to comments $comment = strip_tags($_POST['comment']); print $comment;
if the ($_POST['comment'])
have
<b>Hi..</b> Your</pre> <div class="heading1">article</div> <pre> is <i>awesome.</i>
it will display simply.
Hi.. Your article is awesome.
Now let’s see the of htmlentities function:
//Remove the HTML to comments $comment = htmlentities($_POST['comment']); print $comment;
if the ($_POST['comment'])
have
<b>Hi..</b> Your</pre> <div class="heading1">article</div> <pre> is <i>awesome.</i>
It will display.
<b>Hi...</b> Your</pre> <div class="heading1">article</div> <pre> is <i> awesome. </i>
The character has been changed.
Now the browser will not display the page correctly.
You also need to put a default value to being prevented form XSS.
Make an array of default value. See in the example
if ($_POST['_submit_check']){ $default = $_POST; } else { $default = array('name' => 'abc', 'email' => 'abc@abc.com', 'web' => 'www.google.com', 'content' => 'xyz'); }
See how to set the default value in multiline text area.
print '<textarea name="comment">'; print htmlentities($defalut['comment']); print '</textarea>';
This is how we can prevent of being XSS.