Log in  \/ 
x
Register  \/ 
x

You are here: HomeArticlesSecure User Input PHP Tutorial

Secure Your User's Input

Some of you may or may not be aware that every time you have some "form"(pun intended) of user submitted data your website may be at risk of attack. Some common attacks include SQL Injection and XSS (Cross Server Scripting). But fear not there are ways to validate the information submitted in your forms.

As a web developer I mainly work with open source technologies and this example will be no different focused around PHP. 

When a user submits a form it is sent as either $_POST or $_GET ($_POST is sent to the server) where as $_GET is stored in the URL eg. www.example.com/index.php?name=example&password=123456 with name and password being the information from our form if it was submitted using the <form name="example" action="example.php" method="get"> most of the time we do not want this so we would use POST instead example form would be something like <form name="example" action="example.php" method="post">.

Now that we have some submitted data whatever it may be we need to validate it. The most common method for validating form data without impacting the server is with Javascript however as this can be modified i will stick with server side validation.

Some commands that are important in validating user input are:

a) preg_replace ( )
b) strip_tags( )

how to use these tags

our example.php file might look a little like this

<?php
$user = $_REQUEST['username'] ;
$pass = $_REQUEST['password'] ;
?>

So far all the script is doing is grabing information from the posted fields username and password NOTE: $_REQUEST also grabs information from action="get" not only action="post"

Now we want to ensure that the user cannot place their own code into the field for example something like '"or" 1=1 or other common SQL injection commands this is where we can validate

 

<?php
//Username checks if has value and is not blank
if(isset($_POST['username']&&($user != ''))){
//sets the value of user to the username field and removes invalid chars using the preg_replace function
$user = preg_replace("/[^A-Za-z0-9 ]*/","",$_POST['username']);
}else{
//redirect if error 
header( "Location: http://example.com.au/error.php" );
}//password checks if has value and is not blank
if(isset($_POST['password']&&($pass != ''))){
//then set the variable pass and strip html tags from the password field before hand
($pass = strip_tags($_POST['password'] ));
}else{
//redirect if error 
header( "Location: http://example.com.au/error.php" );
}//Echo the data if successful
echo $user ;
echo "/n" ; 
echo $pass ; 
?>

 

 

And there you have it the basics of server sided form validation please let me know if there are any errors in this code as i wrote this quite quickly I am not sure it is error free.

To explain the above code a little better i have put comments above each line.

Go to top