我如何保护我的Php表格?

时间:2013-09-11 14:14:42

标签: php

下面我有一个运行良好的Php注册表单,但我有点担心因为Sql注入攻击的形式是敞开的,我知道它但是具有非常有限的编码知识来防止它,但仍然学习。

设法添加了一个Captcha以防止机器人自动填写表单并提交,但不幸的是,无法说明能够验证名字和姓氏,我只是想知道如何保护自己反对这种攻击。

相关代码如下所示,谢谢!

1)Check.php

<?php
    session_start();
    $captcha = $_POST['captcha'];
    $captcha_answer = $_SESSION['captcha_answer'];

    if($captcha != $captcha_answer) {
        echo 'Captcha is incorrect!';
    }
    else {
        echo 'Captcha is correct, congratulations! :)';
    }
?>




<?php



    if(isset($_POST['registration']) && $captcha == $captcha_answer)
    {
        require "connection.php";



        $FirstName = strip_tags($_POST['FirstName']);

        $LastName = strip_tags($_POST['LastName']);

        $Msisdn = $_POST['Msisdn'];

        $month = $_POST['month'];

        $day = $_POST['day'];

        $year = $_POST['year'];

        $date = $year . "-" . $month . "-" . $day;

        $dob = date('y-m-d', strtotime($date));

        $Gender = $_POST['Gender'];

        $Faith = $_POST['Faith'];

        $City = $_POST['City'];

        $MarritalStatus = $_POST['MarritalStatus'];

        $Profession =$_POST['Profession'];

        $Country = $_POST['Country'];





    $query="insert into users set FirstName='".$FirstName."',LastName='".$LastName
            ."',Msisdn='".$Msisdn."',dob='".$dob."',Gender='".$Gender."',Faith='".$Faith."',City='".$City."',MarritalStatus='".$MarritalStatus."',Profession='".$Profession."',Country='".$Country."'";


    mysql_query($query)or  die("".mysql_error());   



        echo "Successful Registration!";



            }
?>     

2)Registration.php

</head>

<body>

    </tr>

<div id="div-regForm">

<div class="form-title">Sign Up</div>
<div class="form-sub-title">It's free and anyone can join</div>

    <form method="post" action="check.php" enctype="multipart/form-data">

    <table width="900" align="center" cellpadding = "15">



        <tr>
            <td>FirstName:</td>
            <td><input type="text" name="FirstName" maxlength="10" required="" ></td>

        </tr>
        <tr>
            <td>LastName:</td>
            <td><input type="text" name="LastName" maxlength="10" required=""></td>

2 个答案:

答案 0 :(得分:0)

如果您想保护自己免受SQL注入,请不要使用mysql_ *函数。它们已被弃用,不支持预备语句。

请改用PDO,然后阅读this

答案 1 :(得分:0)

1)你应该使用mysqli object:prepared语句来防止SQL注入。您应该始终在BOTH客户端和服务器端进行检查

简单示例,添加了stmt-&gt; bind_result和stmt-&gt;获取完整性

$mysqli = new mysqli("localhost","root","","dbname");
$stmt = $mysqli->prepare("SELECT * FROM account WHERE username=? and shapass=? LIMIT 1")
$stmt->bind_param("ss",$username,$encrypted_password);
$stmt->execute();
$stmt->bind_result($result1,result2) // assuming table has 2 columns

while( $stmt->fetch() )
{
      //do something
      echo $result1;
      echo $result2;
}