PHP Form Script Security

Some ideas to tighten up form script security … more specifically to counter form spoofing and cross browser attacks.

(1) Check for extra _POST variables, and disallow any _GET variables.

{
$limit_post=count($_POST);
$limit_get=count($_GET);
if ($limit_post>8||$limit_get>0)
{
include (”formhead.php”);
echo “Submission failed.”;
include (”form2.php”);
exit;
}
}

(2) Prevent the exceeding of maximum field length from the server side in the script - setting form field maximum length inputs is not sufficient.

{
$length = strlen($_POST[’Name’] || $_POST[’Email’] || $_POST[’Address’] || etc);
if($length>30)
{
include (”formhead.php”);
echo “Too many characters.”;
include (”form2.php”);
exit;
}
}

(3) Check for legal use of characters (white list approach).

{
if (eregi(”[^-a-z]+$”, $_POST[’Name’]) || eregi(”[^-/\.a-z0-9]+$”, $_POST[’Address’]) || eregi(”[^-a-z]+$”, $_POST[’City’]) etc)
{
include (”formhead.php”);
echo “Invalid characters.”;
include (”form2.php”);
exit;
}
}

(4) Check for well-formed email address.

{
if (!eregi(”^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$”, $_POST[’Email’]))
{
include (”formhead.php”);
echo “Please enter a valid email.”;
$_POST[’Email’]=”";
include (”form2.php”);
exit;
}
}

(5) Use quotemeta to filter output (note that quotemeta doesn’t filter the pipe character - hence the productiveness of using the previous eregi function).

(6) Use the Session token method described at http://shiflett.org/archive/96 to further prevent XSS attacks.

eg.

In the document head:

<?php $token = md5(uniqid(rand(), true));
$_SESSION[’token’] = $token; ?>

In the form:

<input type="hidden" name="sekret" value="<?php echo $token; ?>" />

In the script:

{
if ($_SESSION[’token’] != $_POST[’token’])
{
echo “Invalid submission.”;
//go to error page
exit;
}
}

References:

http://phpsec.org/projects/guide/2.html
http://www.devshed.com/c/a/PHP/Reconsidering-PHP-variables/
http://au.php.net/manual/en/function.quotemeta.php
http://shiflett.org/

Comments are closed.

"Peace is not the product of terror or fear. Peace is not the silence of cemeteries. Peace is not the silent result of violent repression. Peace is the generous, tranquil contribution of all to the good of all. Peace is dynamism. Peace is generosity. It is right and it is duty."

- Oscar Romero
Go to the Top of the Page
Search this Site
Sibagraphics
ABN40098165406 / QLD BN17649330
P.O. Box 259, Pomona, Qld Australia 4568
Ph: +61 (0)7 5485 2085
Mob: +61 (0)412 665 189

Visitor locations

Valid XHTML 1.0 / Valid CSS Copyright | Privacy | Disclaimer
Copyright © 1998 - 2008 Sibagraphics
Page last modified October 11, 2007.