PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP Namespaces

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.

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

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.

Facebook Twitter