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 HTTP & HTTPSPHP 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 NamespacesPHP OOP Autoloading

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.


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.

Visit PHP Help group to get some help from experts.
Profile Picture
Supun Kavinda
I'm the Founder of Hyvor, Web Developer, Physics Lover, Flutist, and a Table Tennis Player.
My Websites