PHP Forms Validation
Preventing XSS Attacks
To preevnt XSS attacks, we need to escape HTML. The built-in PHP function, htmlspecialchars() does it easily.
<script>alert('Hacked')</script> will be converted to <script>alert('Hacked')</script>
htmlspecialchars() function will do the following replacements.
Character | Replacement |
---|---|
& | & |
< | < |
> | > |
" | " |
' | ' |
htmlspecialchars() Example
<?php
$string = '<script>alert("Hello")</script>';
echo htmlspecialchars($string);
Run Example ››Validating The Request Method
It is a good practice to validate the request method. If you are using POST method, you can add following code to the handler.
Tip: die() function terminates the script after echoing its first parameter.
Request Method Validation
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// nice request
} else {
die('Invalid Request');
}
Run Example ››Removing Unnecessary White Spaces
White spaces in the beginning and ending are normally unnecessary. It is pretty simple to remove those spaces with PHP. Just send the string through trim() function.
trim() Example
<pre>
<?php
$text = ' Hello ';
echo $text; // with white spaces
echo '<br>';
echo trim($text); // no white spaces
?>
</pre>
Run Example ››Next chapter will teach you have to create required inputs and create error messages on empty inputs.
Visit PHP Help group to get some help from experts.