Trong bài này mình sẽ giới thiệu về phương thức POST và một số lưu ý quan trọng khi sử dụng phương thức POST trong lập trình web. Như thường lệ trước khi đọc bài này thì bạn nên đọc bài phương thức GET và POST trong PHP đã nhé.

Nội dung chính

  • 1. Phương thức POST là gì?
  • 2. Lấy dữ liệu từ phương thức POST
  • 3. Một ví dụ với phương thức POST
  • 4. Lời kết 

1. Phương thức POST là gì?

Phương thức POST là hình thức client gửi dữ liệu lên server kèm theo dữ liệu và dữ liệu sẽ bị ẩn chứ không hiển thị trên URL như phương thức GET, vì vậy khi xây dựng form lấy thông tin từ user thì ta nên sử dụng phương thức POST vì nó bảo mật hơn.

Ví dụ mình xây dựng form đăng nhập thì mình sẽ sử dụng phương thức POST. Bạn tạo một file tên là post.php và nhập vào đoạn code sau:

XEM DEMO

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
    <head>
        <title>Tinhoccuaem.com - xử lý form với POST</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>tinhoccuaem.com - ứng dụng đăng nhập</h1>
        <form method="post" action="post.php">
            Username: <input type="text" name="username" value=""/> <br/> <br/>
            Password: <input type="post" name="password" value=""/> <br/> <br/>
            <input type="submit" name="btn" value="Đang Nhập"/>
        </form>
    </body>
</html>

 

Bạn hãy thử nhấn đăng nhập và xem trên URL thì sẽ thấy nó không có bổ sung một query string nao vào cả. Như vậy với phương thức POST thì dữ liệu sẽ được giấu đi.

2. Lấy dữ liệu từ phương thức POST

Để lấy dữ liệu từ phương thức POST thì ta sẽ sư dụng biến $_POST, đây là một mảng chứa danh sách tất cả dữ liệu từ client gửi lên bằng phương thức POST.

Quay lại ví dụ trên bạn sửa code lại như sau:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
    <head>
        <title>Tinhoccuaem.com - xử lý form với POST</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>tinhoccuaem.com - ứng dụng đăng nhập</h1>
        <form method="post" action="post.php">
            Username: <input type="text" name="username" value=""/> <br/> <br/>
            Password: <input type="post" name="password" value=""/> <br/> <br/>
            <input type="submit" name="btn" value="Đang Nhập"/>
        </form>
        <?php
        var_dump($_POST);
        ?>
    </body>
</html>

 

Bạn hãy chạy lại chương trình và nhập vào username là ‘tinhoccuaem.com’ và mật khẩu là ‘minhtham’ thì sẽ thấy kết quả như sau:

3. Một ví dụ với phương thức POST

Bây giờ ta xây dựng form đăng nhập hoàn chỉnh nhé.

Giả sử nếu người dùng nhập tên đăng nhập là tinhoccuaem.com và mật khẩu là minhtham thì ta sẽ thông báo là đăng nhập thành công, ngược lại sẽ thông báo đăng nhập sai.

Bạn sửa lại file post.php với nội dung như sau:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
    <head>
        <title>Tinhoccuaem.com - xử lý form với POST</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>tinhoccuaem.com - ứng dụng đăng nhập</h1>
        <form method="post" action="post.php">
            Username: <input type="text" name="username" value=""/> <br/> <br/>
            Password: <input type="post" name="password" value=""/> <br/> <br/>
            <input type="submit" name="btn" value="Đang Nhập"/>
        </form>
        <?php
        if ($_POST['btn'])
        {
            // B1: Lấy thông tin
            $username = isset($_POST['username']) ? $_POST['username'] : '';
            $password = isset($_POST['password']) ? $_POST['password'] : '';
            
            // B2: Kiểm tra dữ liệu
            if (!$password || !$username){
                echo 'Bạn chưa nhập đủ thông tin';
            }
            else if ($password != 'minhtham' || $username != 'tinhoccuaem.com'){
                echo 'Thông tin đăng nhập bị sai';
            }
            else{
                echo 'Đăng nhập thành công!';
            }
        }
        ?>
    </body>
</html>

 

Bạn hãy chạy lại và xem thử thành quả của mình nhé.

Và đây là tấm hình giải thích cho luồng dữ liệu.

4. Lời kết

Như vậy là mình đã giới thiệu xong phương thức POST trong lập trình web, hy vọng qua bài này bạn sẽ không còn thắc mắc POST là gì nữa 🙂

Nếu bài viết có chỗ nào sai thì bạn vui lòng sửa bằng cách comment bên dưới giúp mình nhé, cám ơn các bạn đã đọc.

241 BÌNH LUẬN

  1. Hey there, I think your site might be having browser compatibility issues.
    When I look at your website in Firefox, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, amazing blog!

  2. This design is wicked! You obviously know how
    to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well,
    almost…HaHa!) Wonderful job. I really enjoyed what you had to say, and more than that,
    how you presented it. Too cool!

  3. Terrific work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher! Come on over and visit my website. Thanks =)

  4. magnificent issues altogether, you just won a brand new reader. What might you suggest in regards to your publish that you just made a few days in the past? Any certain?

  5. Thank you for another excellent post. Where else could anybody get that kind of info in such a perfect way of writing? I have a presentation next week, and I am on the look for such info.

  6. I?d must test with you here. Which isn at one thing I often do! I take pleasure in studying a put up that may make individuals think. Additionally, thanks for permitting me to remark!

  7. Whats Happening i am new to this, I stumbled upon this I have found It positively useful and it has aided me out loads. I hope to give a contribution & help other users like its helped me. Good job.

  8. You have made some decent points there. I looked on the net to find out more about the issue and found most people will go along with your views on this website.

  9. Wow! This can be one particular of the most helpful blogs We ave ever arrive across on this subject. Basically Magnificent. I am also an expert in this topic so I can understand your hard work.

  10. Thank you, I ave recently been searching for info about this topic for ages and yours is the best I ave discovered till now. But, what about the bottom line? Are you sure in regards to the supply?

  11. I thought it was going to be some boring old publish, but it really compensated for my time. I will post a link to this page on my blog page. I am sure my visitors will come across that very useful

  12. Usually I do not learn article on blogs, however I wish to say that this write-up very pressured me to try and do so! Your writing style has been surprised me. Thank you, very great article.

  13. I’а†ll immediately snatch your rss feed as I can not to find your email subscription link or newsletter service. Do you have any? Kindly permit me recognise so that I may subscribe. Thanks.

  14. Hey! I know this is kind of off topic but I was wondering if you knew where I
    could find a captcha plugin for my comment form? I’m using the same blog platform as
    yours and I’m having difficulty finding one? Thanks a lot!

  15. First of all I would like to say fantastic blog! I had a quick
    question that I’d like to ask if you do not mind.
    I was curious to find out how you center yourself and clear your mind
    before writing. I’ve had trouble clearing my thoughts in getting my thoughts out
    there. I truly do take pleasure in writing but it just seems like
    the first 10 to 15 minutes are generally lost just trying to figure out how
    to begin. Any recommendations or hints? Kudos!

  16. Attractive section of content. I simply stumbled upon your web site and in accession capital to assert that I acquire actually enjoyed
    account your weblog posts. Any way I will be subscribing in your augment and even I achievement
    you get entry to constantly fast.

  17. You ave made some really good points there. I checked on the net for more information about the issue and found most individuals will go along with your views on this web site.

  18. This is very interesting, You are a very skilled blogger. I ave joined your rss feed and look forward to seeking more of your great post. Also, I have shared your web site in my social networks!

  19. We stumbled over here different web page and thought I might as well check things out. I like what I see so now i am following you. Look forward to checking out your web page for a second time.

  20. I will immediately grab your rss feed as I can not to find your e-mail subscription link or e-newsletter service. Do you ave any? Please allow me realize so that I could subscribe. Thanks.

  21. It’а†s actually a great and useful piece of information. I am glad that you just shared this useful info with us. Please stay us up to date like this. Thanks for sharing.

  22. Your style is really unique in comparison to other people I ave read stuff from. Thank you for posting when you have the opportunity, Guess I will just bookmark this site.

  23. Wow, wonderful blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is magnificent, let alone the content!

  24. It as not that I want to replicate your web site, but I really like the style. Could you tell me which theme are you using? Or was it custom made?

  25. It as essentially a cool and beneficial piece of information. I am content which you just shared this valuable data with us. Please hold us informed like this. Thank you for sharing.

  26. I will immediately grasp your rss as I can at in finding your e-mail subscription link or e-newsletter service. Do you ave any? Please let me know so that I could subscribe. Thanks.

  27. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is excellent, let alone the content!. Thanks For Your article about sex.

  28. Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is wonderful, let alone the content!

  29. I will right away clutch your rss as I can at find your email subscription hyperlink or e-newsletter service. Do you ave any? Please allow me recognise so that I may just subscribe. Thanks.

  30. I thought it was going to be some boring old publish, but it really compensated for my time. I will publish a link to this page on my weblog. I am sure my visitors will find that really useful

  31. Wonderful work! That is the type of info that should be shared around the internet. Shame on Google for no longer positioning this put up upper! Come on over and consult with my website. Thank you =)

  32. Wow! This could be one particular of the most helpful blogs We have ever arrive across on this subject. Actually Wonderful. I am also an expert in this topic therefore I can understand your hard work.

  33. I think other web site proprietors should take this website as an model, very clean and wonderful user genial style and design, let alone the content. You are an expert in this topic!

  34. Normally I do not learn article on blogs, however I wish to say that this write-up very compelled me to take a look at and do so! Your writing style has been amazed me. Thanks, quite great article.

THOÁT KHỎI BÌNH LUẬN

Please enter your comment!
Please enter your name here