How to Prevent Cross Site Scripting with PHP


In this article, we show how to prevent cross site scripting with PHP.

Cross site scripting is when a user is able to insert the elements of a language onto a web page such as HTML or Javascript.

For example, if you have a text box on your page where a user can enter input into the text box, the user can insert direct HTML tags onto the page or write Javascript to the page.

To prevent this cross site scripting from happening, PHP has a built-in function, htmlentities(), that prevents a user from being able to enter direct HTML tags or Javascript onto the page.

To visualize this and actually see it, use the text box shown below. Enter in a regular string such as "hello" and then enter in an HTML tag such as <h1>hello</h1>. You'll see that direct, without the htmlentities() function, you get the transcribed HTML code, so you see a heading with the content of hello. With the htmlentities() function, you get the literal value printed out. So what's printed out is <h1>hello</h1>. With the htmlentities() function, the language, whether HTML or Javascript will not be executed, so you get the literal value just as entered.


So to do this in PHP, we use the following code below.

So we create a string and we pass this string through the htmlentities() function. This htmlentities() function prevents any other languages such as HTML and Javascript from being actually rendered in the language.

This helps to protect a site that may not want users to be able to directly add any HTML or Javascript to be added to a page.

Related Resources

How to Create an XML Document with PHP

How to Parse an XML Document Using PHP

HTML Comment Box is loading comments...