PHP Sanitisation

by | May 9, 2019 | Featured, Guides, Habib Featured, Habib O

PHP Sanitisation

In this little guide/post we will cover the basics of sanitisation in PHP, with some code snippets and why you should use them.

User inputted data.

If a user inputs data onto your site directly into a mysql database, it can often be a direct point of vulnrability. The user can put anything into a field that is not sanitised allowing that data to be displayed back. Lets take for example if a user registers with “Hello” it will display back “Hello”, however if a user registers with <h1>Hello</h1> it will display Hello¬†actually parsing the HTML code, this is a big problem as you are directly allowing code to be ran onto your side, this can lead to XSS and SQLI injection. The aim of sanitisation is to take the inpuit and stop it causing issues. If the request was sanitised it would display back “<h1>Hello</h1>” not actually processing it. There are many inbuilt sanitsation functions within MYSQL, PHP, and PDO. For example “FILTER_SANITIZE_EMAIL" This will sanitise email input only allowing letters digits and !#$%&’*+-=?^_`{|}[email protected][]. These symbols.

For a full list of inbuilt PHP sanitisation check out – https://www.php.net/manual/en/filter.filters.sanitize.php another great resource is https://www.w3schools.com/php/php_filter.asp

Through out my code i have two snippets that i personally use for sanitisation which i will show you below.

 

The code above is my escape function, i use this on every part of code where data is being read or submitted to the database. It parses the code into UTF-8 format.

For example i could have a variable such as

$acctype = $_GET[‘type’];

Which would then be changed to

$acctype = escape($_GET[‘type’]);

Just incase any data has been tampered with or played with, this will stop the majority of XSS and SQLI injections.

I also use another function for input filtering, this one works in a different way, if any of the input types are detected it will redirect and die stopping the code from being processed.

An example use would be for post requests, this function can be used along side the escape function, to detect and sanitize. If the input from the request contains any of the symbols it will be redirected. Here is an example on how to use it.

$acctype = escape($_GET[‘type’]);

filterinput($acctype);

This was just a little tutorial on good programming practices to secure your software. Hope you enjoyed

 

Habib O

Self proclaimed tech enthusiast looking to expand my personal portfolio. Click my profile to find out more. PS. If you give me something i will break it.