PHP Input Filtering

PHP is one of the easy handling languages which makes developers be comfortable to work with. On the other hand, it is easy to hack the code from outside. Since web applications accept data from outsiders spread among the world, we need to validate such data, before allowing it to our PHP application, for security purpose.

Filtering can be done with client side by using javascript, VB script and etc. But, this kind of client-side filtering is used to validate the data that are posted using HTML forms of our application. Even though this validation filters form data, it is not only enough for guaranteed integrity.


For that, PHP input filtering mechanism provides additive security to our web application from malicious access. For example, the following form is used to accept the subscription request from the user.

<script type="javascript">
function fnSubscribe() {
return false;
return false;
return true;
<form name="frmSubscription" action="subscribe.php" method="GET" onSubmit="return fnSubscribe()">
<input type="text" name="userName"/><br/>
<input type="text" name="userEmail"/><br/>
<input type="submit" name="subscribe" value="Subscribe" />

The user who want to subscribe using this form, are required to enter their username and email address. These two inputs are mandatory and can be validated by the javascript function fnSubscribe(). If any one of the required input is empty, then the script fails to submit form data to PHP page named subscribe.php. This is the way to filter at the client side.

But, the user can directly access subscribe.php without any required input data by entering the following URL.


When some intruders try with the above URL, then the subscription will be done successfully without user’s email address. So we need to apply such filtering at server side also. For that, subscribe.php should be written as shown below.

$userName = $_GET["userName"];
$userEmail = $_GET["userEmail"];
if($userName!="" and $userEmail!="") {
$conn = mysql_connect("localhost","root","");
mysql_query("INSERT INTO subscribers (userName, userEmail) VALUES ('" . $userName . "', '" . $userEmail . "')",$conn);

The conditional statements are added to check if the required fields are not empty or not. Now, subscribe.php can filter anonymous input data from intruders who try to access database to create a subscription entry improperly.

PHP provides several built-in functions to check the input data format by using pattern matching techniques. So, all the client side validation can be done one again in server side by using input filtering to provide integrity for the web pages.

Download PHP Input Filtering Source Code

This PHP code tutorial was published on May 18, 2013.

↑ Back to Top