如何正确保护表单 - 平面文件数据库

时间:2011-11-25 11:49:21

标签: php javascript security flat-file

我的表单将用户输入(输入+ textarea)保存到平面文件数据库中。 我发现了许多关于如何创建平面文件数据库的例子,但是没有人能够正确地介绍如何从XSS和其他恶意攻击中正确保护表单的一些基础知识。

我知道最好的方法是让(Ex :)成为一个SQL数据库......但事实并非如此。

到目前为止,我知道(这可能是错的!如果是的话请纠正我):

  • 最好使用.php文件存储数据(在<?php ...data... ?>内)而不是.txt文件
  • 如果可能,请在数据库文件夹
  • 中删除带有deny from all的.htaccess
  • 在提交前通过php验证您的输入和textarea。 (但是如何做到这一点???我的意思是......什么是最好的方式?
  • 正确验证您的字段(php)(究竟......某些做法仅针对sql数据库,而不是针对ffdb ...
  • 我看起来像mysql_real_escape_string,但对于ffdb
  • 已经足够了

你有什么想法? 感谢您的帮助

2 个答案:

答案 0 :(得分:2)

Dunno你从哪里得到它,但是使用

  
      
  • .php文件存储数据(内部)而不是.txt文件
  •   

你可以肯定它会允许任何人,无论他们想要什么攻击,

  
      
  • 从数据库文件夹内的所有内容中删除.htaccess
  •   

绝对没有意义,

所以,似乎唯一的问题是

  
      
  • 如何从XSS正确保护表单
  •   

并使用htmlspecialchars()

解决

这里是我很久以前在很远的一个星系中写的这样一个脚本的例子...... 如果看起来不清楚,请随时询问。

<?php
if ($_SERVER['REQUEST_METHOD']=='POST') { 
  // iterating over POST data
  foreach($_POST as $key => $value) { 
    //first we are doing non-destructive modifications
    //in case we will need to show the data back in the form on error
    $value = trim($value); 
    if (get_magic_quotes_gpc()) $value = stripslashes($value); 
    $value = htmlspecialchars($value,ENT_QUOTES); 
    $_POST[$key] = $value; 
    //here go "destructive" modifications, specific to the storage format
    $value = str_replace("\r","",$value);
    $value = str_replace("\n","<br>",$value);
    $value = str_replace("|","&brvbar;",$value);
    $msg[$key] = $value;
  } 
  //various validations
  $err=''; 
  if (!$msg['name']) $err.="You forgot to introduce yourself<br>"; 
  if (!$msg['notes']) $err.="You forgot to leave a comment!<br>"; 
  //and so on
  //...
  // if no errors - writing to the file
  if (!$err) { 
    $s  = $msg['name']."|".$msg['email']."|".$msg['notes']."|".time()."\n"; 
    $fp = fopen("gbook.txt","a"); 
    fwrite($fp,$s); 
    fclose($fp); 
    //and then redirect
    Header("Location: ".$_SERVER['PHP_SELF']); 
    exit; 
  } 
  //otherwise - show the filled form
} else { 
  //if it was not a POST request
  //we have to fill variables used in form
  $_POST['name'] = $_POST['email'] = $_POST['notes'] =''; 
} 
?> 
<html> 
<head></head> 
<body> 
<? if ($err): ?><font color=red><b><?=$err?></b></font><? endif ?> 
<form method="POST">
Name: <input type="text" name="name" value="<?=$_POST['name']?>"><br> 
Email: <input type="text" name="email" value="<?=$_POST['email']?>"><br> 
Notes: <textarea rows="3" cols="30" name="notes"><?=$_POST['notes']?></textarea><br> 
<input type="submit" name="submit"> 
</form> 
</body> 
</html>

它将生成一个所谓的管道分隔格式,如此

name1|email1|comment
name2|email2|comment

你可以使用file()+ explode()

来阅读它

答案 1 :(得分:1)

如果您在文本文件中存储内容,则无需担心转义字符串。

您可以过滤恶意HTML,但这取决于您对内容的处理方式。

确保该文件位于公共目录之外的文件夹中,或者使用deny from all htaccess技巧进行保护,并确保使用文件锁定来防止它同时被覆盖。

此外,如果您正在寻找一个好的平面文件数据库,请查看Flintstone,我写的一个键/值数据库存储可能对您有用。

相关问题