DONATE Hyvor Developer
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

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 &lt;script&gt;alert('Hacked')&lt;/script&gt;

htmlspecialchars() function will do the following replacements.

Character Replacement
& &amp;
< &lt;
> &gt;
" &quot;
' &#039;

htmlspecialchars() Example

$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

	// 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


$text = '   Hello  ';

echo $text; // with white spaces
echo '<br>';
echo trim($text); // no white spaces


Run Example ››

Next chapter will teach you have to create required inputs and create error messages on empty inputs.