I have the following PHP code:
<?php
$comentario = "<strong>Puedo mostrar esto en negrita >:)<strong>"; //Esto es extraído de la base de datos.
?>
<div id="comment">
<?php echo $comentario; ?>
</div>
The output would be:
I can show this in bold >:)
In this example it is something basic, but it is possible to insert more dangerous scripts that affect a web application in the same way.
The output I want is as it is as a user writes it, example:
<strong>Puedo mostrar esto en negrilla >:)</strong>
I appreciate your responses.
You must make use of a function called
htmlspecialchars()
(or alsohtmlentities()
) to convert characters with special meaning in HTML (such as<
,>
, etc) into HTML entities (<
,>
, etc).Your code would look like this:
Also, for your knowledge, not protecting yourself from this kind of thing makes your page vulnerable to XSS (cross-site scripting) attacks . I'm glad you realized for yourself the danger.
Htmlspecialchars is bad. And even if it were good it would still be very vulnerable to xss.
Block inline javascript, unsafe eval, use text nodes, use prepared statements...
Without being a security expert (and not even being one) it is practically impossible to make a secure application. If this were the case, there would be no security flaws in applications and websites such as Google Search.
Well, imagine a junior programmer with basic notions.
The best thing is that before putting the application into production accepting real input, you release a sanboxed version in docker with a bughunting program. You don't need to pay anything. You can create a hall of fame or thanks section on your site or sign up for a free bughunting page where cybersecurity students can use your app to learn and test things. Or gain reputation on the site.