I am learning php and I came across htmlspecialchars() that it is used to prevent hackers attack , How ? I have read it on google , did not understand yet.Can you please give an example how ?
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
Website : <input type="text" name="website"><br>
<input type="submit" value="Submit" name="button">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$website = $_POST['website'];
echo "true";
if(empty($website)){
echo "empty";
}
else{
echo $website;
}
}
?>
when I enter a url like this http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
the output is
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
when I remove the htmlspecialchars()
from
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
the output is same . Why ? what is the use of htmlspecialchars()
then ??
and
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
In this case, the above code will be translated to: (how and where this happens ?)
<form method="post" action="test_form.php/"><script>alert('hacked')</script>
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
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.
Result