July 4, 2010

How to do Php Security check for input fields and input treatment?

Question by Yosef

How to do Php Security check for input user fields and input user treatment(please if you can solve example1+2)?

Example1: check if user insert url or something else:

<label>url: </label>
<input type="text">

Example2: check if user insert html or something else

<label>paste html: </label>
<textarea></textarea>

thanks

Answer by h3xStream

1. For the validation of URLs :

$validUrl = strpos($url, "http://") === 0;
if(!$validUrl) $url = "http://".$url;

When the link is return to the user, use htmlentities().

2. For the validation of HTML code, use a lib like http://htmlpurifier.org/.

<?php
require_once 'htmlpurifier/HTMLPurifier.auto.php';

$purifier = new HTMLPurifier();
$clean_html = $purifier->purify($_GET['dirty_html']);
echo $clean_html;
?>

With the input :

<img src="test.gif" onload="alert('xss')"/>

The result is :

<img src="test.gif" alt="test.gif" />

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!