When to Use HTMLspecialchars() Function

when to use htmlspecialchars() function?

You should only call this method when echoing the data into HTML.

Don't store escaped HTML in your database; it will just make queries more annoying.

The database should store your actual data, not its HTML representation.

When to use: htmlspecialchars?

You should sanitize data before inserting it into a database, and escape it on retrieval.

htmlspecialchars is used for escaping, so it should be after you’ve fetched it from the database.

Do i use the htmlspecialchars correctly?

htmlspecialchars encodes html characters, for example <tag> will be replaced with <tag>. When you load that string back from database and display it, the browser will still display <tag> as <tag>, but it won't be treated as html instruction by the browser. So in the page source, you will still see the encoded <tag>.

If you want to use the string on the page so it gets interpreted as normal html command, you have to use htmlspecialchars_decode (Docs) to convert it back after you loaded the content back from the database.

loaded_from_db = htmlspecialchars_decode(value);

If you want to escape your input because of security considerations to protect you from sql injections, you could use mysqli_real_escape_string instead.

But using prepared statements would be the best choice, because you define exactly what you expect as parameters for your statements and the values provided cannot mess it up. It's also the recommended approach even if it's just for testing purpose and it's not that hard to implement.

so your example with mysqli and prepared statements would be:

$stmt = $mysqli->prepare("UPDATE playerstats SET message=? WHERE id = ?");    
$stmt->bind_param("si", $post, $id)
$stmt->execute()

note that I didn't include any error handling.

use of htmlspecialchars()

If you don't use htmlspecialchars() the attacker may execute the code especially javascript.

From your code try submitting the form with <h1>Hello, World!</h1> as input the result will be

Hello, World

and to prevent this type of attack we use htmlspecialchars()

Without htmlspecialchars() the code gets executed

and also submit <script>alert('alert');</script> the result will be alert box

provide <script>alert('alert');</script> in textbox and submit.

Sample Image

Result
Sample Image

How to use htmlspecialchars() function on a php contact form (that is using the mail() function)

The htmlspecialchars() function is used for escaping special characters to prevent possible XSS attacks if you use this function the correct way. You may want to use this function for the message.

For example:

mail("example@example.com", "Contact Message", "Name: ".htmlspecialchars($_POST['name'])."
Email: ".htmlspecialchars($_POST['email'])."
Telephone: ".htmlspecialchars($_POST['telephone'])."
Company: ".htmlspecialchars($_POST['company'])."
Budget: ".htmlspecialchars($_POST['budget'])."
Message: ".htmlspecialchars($_POST['message']));

{
$_POST= array();
$result='<div class="alert thankyou" role="alert">THANK YOU! WE\'LL BE IN TOUCH SHORTLY...</div>';
}

Any html you have in your message will be escaped. I suggest you to read this article aswell to get a full understanding on how to use this function properly. When used correctly, is htmlspecialchars sufficient for protection against all XSS?

Should I be using htmlspecialchars?

There are (from a security POV) three types of data that you might output into HTML:

  • Text
  • Trusted HTML
  • Untrusted HTML

(Note that HTML attributes and certain elements are special cases, e.g. onclick attributes expect HTML encoded JavaScript so your data needs to be HTML safe and JS safe).

If it is text, then use htmlspecialchars to convert it to HTML.

If it is trusted HTML, then just output it.

If it is untrusted HTML then you need to sanitise it to make it safe. That generally means parsing it with a DOM parser, and then removing all elements and attributes that do not appear on a whitelist as safe (some attributes may be special cased to be filtered rather than stripped), and then converting the DOM back to HTML. Tools like HTML Purifier exist to do this.

$course->homepage = $_POST['homepage']; // may contain unsafe HTML

I would like that $course->homepage be treated and rendered as HTML by the browser.

Then you have the third case and need to filter the HTML.

is it necessary to use htmlspecialchars in laravel controller when request is get

Long answer in short 'NO', Maintain your cart data in session unless it needs to retain for later use. Always use binding so you do not have to do extra work or long dirty code.

In Laravel binding can be done easily like this

$cart = new Cart;
$cart->productId = $request->productId;
$cart->userId = $user->id;
$cart->actualPrice = $product->actualPrice;
$cart->price = $request->price;
$cart->save();

It will do the magic for you.

Should I use htmlspecialchars inside a tag

htmlspecialchars is a function to escape certain characters which have a special meaning in HTML. For example, if you wanted to embed a value which contains quotes inside an HTML attribute:

<a title="Simon says "Hello World"">

This obviously breaks the HTML syntax. You need to apply the escaping function to the value Simon says "Hello World" to arrive at:

<a title="Simon says "Hello World"">

This is now correct HTML syntax.

The same goes for values containing < or > in regular text, because those can obviously be interpreted as HTML tags. Read The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for more on the topic.

You need to do this the same way for all HTML tags and values.

printf('<a href="%s" title="%s">%s</a>',
htmlspecialchars($url),
htmlspecialchars($title),
htmlspecialchars($content));

URLs have their own escaping rules, you may have to URL encode values you put into a URL before you put it into HTML:

$url = sprintf('/foo/%s', urlencode($bar));
printf('<a href="%s">...</a>', htmlspecialchars($url));

Should you use htmlspecialchars() before isset() and empty(), or after?

Well, think about it this way. Why do we use isset in the first place? The answer is to protect our code from trying to do things with something that doesn't exist.

For example, using php -a in your console, you can see:

php > $temp
php > echo htmlspecialchars($temp);

Parse error: parse error in php shell code on line 2
php >

Clearly you don't want your code throwing parse errors. So, you need to check that the value exists first (using isset), then do things with that value.



Related Topics



Leave a reply



Submit