Jump to content

What is the BEST/EASIEST way to secure a form with PHP


stewart715

Recommended Posts

Let's say you have a simple HTML form with action through a PHP file to store the information in a MySQL database. What is the best/easiest way to secure that form procoess so the form cannot just be stored in any HTML file on a remote server and submitted?
Still, the referrer can be manipulated and should never be used as part of a security environment.

I would rather go for a solution where the form contains a db stored random string, and upon submitting the form the posted string is compared with the db-stored string.

Example:
[code]

<?php

if(isset($_POST['my_button']) && !empty($_POST['rand_key'])) // check form
{
  $rand_key = htmlspecialchars($_POST['rand_key']);
  $delete_old = mysql_query("delete from rand_keys where time_set < date_sub(now(), interval 3600 second)"); // one hour expire time on each key
  $check_this = mysql_query("select id from rand_keys where rand_key = '$rand_key'");
  if(mysql_num_rows($check_this) <> 1)
  {
    die("Form not accepted");
  }
 
  // proceed with other form todo's
}
else // show form
{
$rand_key = md5(mktime()*rand());
$insert_it = mysql_query("insert into rand_keys (time_set, rand_key) values (now(), '$rand_key')");

echo <<<_HTML

<form method="post" action="this.php">
<input type="hidden" name="rand_key" value="$rand_key" />
<input type="text" name="whatever" />
<input type="button" name="my_button" value="Send Me!" />
</form>

_HTML;
}

?>

[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.