Thứ Hai, 22 tháng 6, 2015

Tạo mã xác nhận cho form đăng ký thành viên

Ở bài trước, tôi đã giới thiệu các bạn Kiểm tra tính hợp lệ của dữ liệu để giúp chúng ta kiểm tra thông tin từ người dùng một cách chính xác nhất. Nhưng khi kiểm tra như vậy vẫn chưa đủ an toàn cho website của chúng ta vì một phần mềm dễ dàng nhập thông tin hợp lệ vào các trường thông tin đó. Vì vậy chúng ta phải tìm cách để ngăn chặn các spam đó trong quá trình lập trình php.

Trong bài này, chúng ta tiếp tục tìm hiểu phương pháp tạo dãy số ngẫu nhiên để chống tấn công flood dữ liệu. Hoặc ai đó cố tình spam khiến cơ sở dữ liệu của chúng ta không thể xử lý tiếp được.

Trong file index.php chúng ta sẽ thêm ô input nhập captcha và ảnh captcha như sau:

[codesyntax lang=”php”]

<div class="user_text">

                           <label class="lable_text">Mã xác nhận:</label> <input

                                  type="text" name="user_captcha" id="captcha"

                                  autocomplete="off" value="">

</div>
[/codesyntax]

Tạo file captcha.php có nội dung như sau:

[codesyntax lang=”php”]

<?php

session_start();

function create_image()

{

       $md5_hash = md5(rand(0,999));

       $security_code = substr($md5_hash, 15, 5);

       $_SESSION["security_code"] = $security_code;

       $width = 100;

       $height = 25;

       $image = ImageCreate($width, $height);

       $white = ImageColorAllocate($image, 255, 255, 255);

       $black = ImageColorAllocate($image, 0, 0, 0);

       ImageFill($image, 0, 0, $black);

       ImageString($image, 5, 30, 6, $security_code, $white);

       header("Content-Type: image/jpeg");

       ImageJpeg($image);

       ImageDestroy($image);

}

create_image() ;

exit();

?>
[/codesyntax]



Đọa code trên có nhiệm vụ là tạo ra một chuỗi bất kỳ có 5 ký tự gán vào $_SESSION[“security_code”] và hiển thị chuỗi trên một khung có kích thước 100 x 25px Bạn vào trình duyệt ọi file index.php sẽ có kết quả:


Bây giờ chúng ta sẽ kiểm tra khi người dùng bấm nút đăng ký ( bạn nhớ thêm kiểm tra xem đã nhập captcha chưa nhé! )

Lúc đó chúng ta sẽ só sánh mã xác nhận so với $_SESSION[“security_code“]. Nếu giống nhau thì chúng ta lưu vào cơ sở dữ liệu. ngược lại thì thông báo lỗi yêu cầu nhập lại.

Và đoạn code xử lý như sau:

[codesyntax lang=”php”]

<?php

session_start();

$name='';

$pass='';

$email='';

$name_err="";

$captcha_err="";

include 'config.php';

if(isset($_POST['dangky']))

{  

       $name=$_POST['user_name'];

       $pass=$_POST['user_pass'];

       $email=$_POST['user_email'];



if($_POST['user_captcha'] == $_SESSION['security_code'])

{

     $query="SELECT * FROM tbl_user WHERE user_name='".$name."'";

     $result=mysql_query($query);



     if(mysql_num_rows($result)>0){

            $name_err="Tên đăng nhập đã tồn tại";

     }else{

            $query="INSERT INTO tbl_user (user_name,user_password,user_email) VALUES ('".$user_name."','".md5($user_pass)."','".$user_email."')" ;



            $result=mysql_query($query);



     }

}

else

{

   $captcha_err="Bạn nhập sai mã xác nhận";

}

}

?>
[/codesyntax]



Và toàn bộ file index.php của chúng ta có nội dung như sau:

[codesyntax lang=”php”]

<?php

session_start();

$name='';

$pass='';

$email='';

$name_err="";

$captcha_err="";

include 'config.php';

if(isset($_POST['dangky']))

{  

       $name=$_POST['user_name'];

       $pass=$_POST['user_pass'];

       $email=$_POST['user_email'];



if($_POST['user_captcha'] == $_SESSION['security_code'])

{

     $query="SELECT * FROM tbl_user WHERE user_name='".$name."'";

     $result=mysql_query($query);



     if(mysql_num_rows($result)>0){

            $name_err="Tên đăng nhập đã tồn tại";

     }else{

            $query="INSERT INTO tbl_user (user_name,user_password,user_email) VALUES ('".$user_name."','".md5($user_pass)."','".$user_email."')" ;



            $result=mysql_query($query);



     }

}

else

{

   $captcha_err="Bạn nhập sai mã xác nhận";

}

}

?>



<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Insert user</title>

<script type="text/javascript"

       src="http://code.jquery.com/jquery-latest.js"></script>

<style type="text/css">

.user_text {



       margin: 10px;



       overflow: hidden;



}

.user_bottom{

       width: 387px;

       text-align: center;



}

.thongbao{

       width: 250px;

       float: left;

}

.thongbao3{

       width: 136px;

       float: left;

       margin-left: 30px;

}

.lable_text {

       width: 150px;

       float: left;

}



.classtext {

       float: left;

       width: 300px;

}



.error {

       color: red;

}



.success {

       color: blue;

}

.wapper{

       width: 800px;

       margin: auto;

}

#captcha{float: left;}

</style>

<script src="validate/jquery.js"></script>

<script src="validate/jquery.validate.js"></script>

       <script type="text/javascript">

       $().ready(function() {

       $("#signupForm").validate({

              rules: {

                     // xay dung cac tap luat

                     username: {

                           required: true,

                           minlength: 3

                     },

                     user_pass: {

                           required: true,

                           minlength: 5

                     },

                     user_pass2: {

                           required: true,

                           minlength: 5,

                           equalTo: "#user_pass"

                     },

                     user_email: {

                           required: true,

                           email: true

                     },

                     user_captcha: {

                           required: true

                           }





              },

              messages: {

                     user_name: "Vui lòng điền tên đăng nhập",



                     username: {

                           required: "Vui lòng điền tên đăng nhập",

                           minlength: "Tên đăng nhập tối thiểu 3 ký tự"

                     },

                     user_pass: {

                           required: "Vui lòng điền tên mật khẩu",

                           minlength: "Mật khẩu tối thiểu 5 ký tự"

                     },

                     user_pass2: {

                           required: "Vui lòng nhập lại mật khẩu",

                           minlength: "Mật khẩu tối thiểu 5 ký tự",

                           equalTo: "Nhập lại mật khẩu chưa chính xác"

                     },

                     user_email:{

                           required: "Vui lòng nhập email",

                           email: "Email chưa đúng định dạng"

                     },

                     user_captcha: {

                           required: "Vui lòng nhập mã xác nhận"

                           }





              }

       });

});

       </script>

<script type="text/javascript">

       $(document).ready(function() {



              // Sự kiện khi nhập vào user_name

              $("#user_name").keyup(function() {



                     if ($(this).val() != '') {

                           // Gán text cho class thongbao trước khi AJAX response

                           $(".thongbao").html('checking username...');

                     }

                     // Dữ liệu sẽ gởi đi

                     var form_data = {

                           action : 'check_user',

                           user_name : $(this).val()

                     };



                     $.ajax({

                           type : "POST", // Phương thức gởi đi

                           url : "data.php", // File xử lý dữ liệu được gởi

                           data : form_data, // Dữ liệu gởi đến cho url

                           success : function(result) { // Hàm chạy khi dữ liệu gởi thành công

                                  $(".thongbao").html(result);



                           }

                     });



              });



       });

</script>



</head>

<body>

<div class="wapper">



       <form method="post" name="fcheck" id="signupForm" action="index.php">



              <div class="user_text">

                     <h2>Đăng ký thành viên</h2>

                     <div class="user_text">

                           <label class="lable_text">Tên đăng nhập:</label> <input type="text"

                                  class="classtext required" name="user_name" id="user_name"

                                  autocomplete="off" value="<?php echo $name;?>">

                           <div class="thongbao"><?php echo $name_err;?></div>

                     </div>

                     <div class="user_text">

                           <label class="lable_text">Mật khẩu:</label> <input type="password"

                                  class="classtext" name="user_pass" id="user_pass"

                                  autocomplete="off" value="">

                           <div class="thongbao1"></div>

                     </div>

                     <div class="user_text">

                           <label class="lable_text">Xác nhận mật khẩu:</label> <input

                                  type="password" class="classtext" name="user_pass2" id="user_pass2"

                                  autocomplete="off" value="">

                           <div class="thongbao2"></div>

                     </div>

                     <div class="user_text">

                           <label class="lable_text">Email:</label> <input

                                  type="email" class="classtext" name="user_email" id="user_email"

                                  autocomplete="off" value="<?php echo $email;?>">

                           <div class="thongbao3"></div>

                     </div>

                     <div class="user_text">

                           <label class="lable_text">Mã xác nhận:</label> <input

                                  type="text" name="user_captcha" id="captcha"

                                  autocomplete="off" value="">

                           <div class="thongbao3"><img src="captcha.php" /></div><span><?php echo $captcha_err;?></span>

                     </div>

                     <div class="user_bottom" >

                     <input type="submit" id="btn" name="dangky" value="Đăng ký">

                     </div>

              </div>



       </form>

</div>

</body>

</html>
[/codesyntax]

SHARE THIS

0 nhận xét:

Lưu ý: Chỉ thành viên của blog này mới được đăng nhận xét.