提供表格的安全方式

时间:2014-03-12 22:04:07

标签: php mysql forms

答案将被发送到mysql数据库。

有没有更好的方法来做到这一点,让它更安全?

<form action="insert.php" method="post">

1. Artist Name: <input type="text" name="artist" />

2. Song Name: <input type="text" name="song" />

<input type="submit" />

</form>

1 个答案:

答案 0 :(得分:1)

如果您想要从外部/第三方网站提交保护表单,那么您需要向表单添加CSRF令牌,并使表单键与发布的内容无关。

例如,在您的表单上:

<?php 
session_start();
$_SESSION['csrf']        = uniqid(microtime(true));
$_SESSION['artistParam'] = uniqid(microtime(true));
$_SESSION['songParam']   = uniqid(microtime(true));
?>
<form action="insert.php" method="post">
    <input type="hidden" name="csrf" value="<?php echo $_SESSION['csrf'];?>"/>
    1. Artist Name: <input type="text" name="<?php echo $_SESSION['artistParam'];?>" />
    2. Song Name: <input type="text" name="<?php echo $_SESSION['artistParam'];?>" />
    <input type="submit" />
</form> 

现在在接收器文件 insert.php 上,您将检查是否已设置所需参数并匹配会话变量..例如:

<?php 
session_start();

if(
    //Check is POST
    $_SERVER['REQUEST_METHOD'] == 'POST' &&

    //Check required variables are set
    isset($_SESSION['csrf']) &&
    isset($_SESSION['artistParam']) &&
    isset($_SESSION['songParam']) &&
    isset($_POST['csrf']) &&
    isset($_POST[$_SESSION['artistParam']]) &&
    isset($_POST[$_SESSION['songParam']]) &&

    //Check csrf key match the session key
    $_SESSION['csrf'] == $_POST['csrf']
){
    //do somthing with values
    $artist = $_POST[$_SESSION['artistParam']];
    $song   = $_POST[$_SESSION['songParam']];
}

//Unset to stop multiple attempts
unset($_SESSION['csrf'], $_SESSION['artistParam'], $_SESSION['songParam']);
?>

你甚至可以使用javascript(比特矫枉过正)对表单进行编码。

<?php 
$form = '<form action="insert.php" method="post">
    <input type="hidden" name="csrf" value="'.$_SESSION['csrf'].'"/>
    1. Artist Name: <input type="text" name="'.$_SESSION['artistParam'].'" />
    2. Song Name: <input type="text" name="'.$_SESSION['artistParam'].'" />
    <input type="submit" />
</form>';

$str = preg_replace('/^\s+|\n|\r|\s+$/m', '', $form);
$enc = '';
for ($i=0; $i < strlen($str); $i++){
    $hex = dechex(ord($str[$i]));
    $enc .= ($hex=='') ? $enc.urlencode($str[$i]) : '%'.(strlen($hex)==1 ? '0'.strtoupper($hex) : strtoupper($hex));
}
$enc = str_replace(array('.','+','_','-'),array('%2E','%20','%5F','%2D'),$enc);
$sec = substr(sha1(microtime(true)),0,10);
echo '<script type="text/javascript">var x'.$sec.'x="'.$enc.'";document.write(unescape(x'.$sec.'x));</script>
    <noscript>
        <style>
            #noscript_notice {
                text-align: center;
                font-weight: bold;
                color:#FF6962;
                padding-top: 20px;
            }
        </style>
        <div id="noscript_notice">
            <p>Please enable JavaScript!</p>
        </div>
    </noscript>';
?>

这是你的意思吗?