Trong bài này chúng ta tìm hiểu về hàm header, đây là một hàm được dùng khá nhiều trong lập trình web, ví dụ như dùng để chuyển hướng trang, dùng để khai báo định dạng file trả về từ Server, …

Trong tiếng anh thì có định nghĩa như sau: header() is used to send a raw HTTP header, khái niệm này bạn hãy tự dịch ra chứ mình cũng không biết dịch sao cho sát nghĩa nữa :3

Cú pháp của hàm header như sau:

 

1 header ($string, $replace = true, $http_response_code = null) {}

 

Trong đó:

  • $string: Chuỗi khai báo cho kết quả trả về từ Server, chuỗi này đóng vai trò quan trọng nhất vì nội dung của nó sẽ quyết định header sẽ làm gì.
  • $replace: Tham số này mặc định là true, nghĩa là định dạng của chuỗi $string sẽ được replace chứ không phải khai báo mới (trường hợp khai báo nhiều header).
  • $http_response_code: Mã code trả về từ Server. VD 404 là not found 301 là chuyển hướng có chủ đích

Lưu ý: Cũng như Session trong PHP, bạn phải chắc chắn rằng ở phía trên đoạn code sử dụng header không được xuất ra bất kì một ký tự nào, vì vậy thông thường chúng ta đặt header ở phía trên cùng của file, nơi mà chưa có những đoạn mã HTML.

Và bây giờ chúng ta tìm hiểu một số công dụng của hàm header nhé.

Nội dung chính

  • 1. Header điều hướng trang
  • 2. Khắc phục lỗi font với hàm header
  • 3. Khai báo định dạng file
  • 4. Lời kết
  1. Header điều hướng trang

Bạn có thể sử dụng thẻ header để điều hướng, chuyển hướng trang với cú pháp như sau:

 

1 header(‘Location: http://www.taynguyenduki.com/’);

 

Ví dụ: Chuyển hướng tới trang tinhoccuaem.com

 

1 header(‘Location: http://www.tinhoccuaem.com/’);

 

Khi chuyển hướng trang với hàm header bạn nên khai báo thêm response_code sẽ tốt hơn rất nhiều cho SEO. Chẳng hạn như bạn thay đổi domain cho website thì khi người dùng vào domain cũ bạn sẽ chuyển hướng nó sang domain mới, lúc này bạn nên sử dụng code là 301 vì đây là code khai báo chuyển hướng có điều kiện.

 

1 header(‘Location: http://www.taynguyenduki.com/’, true, 301);

 

Còn trường hợp bạn muốn chuyển hướng page not found thì hãy sử dụng mã code 404.

 

1 header(‘Location: http://www.taynguyenduki.com/’, true, 404);

 

  1. Khắc phục lỗi font với hàm header

Bạn có thể sử dụng hàm header để khắc phục tình trạng lỗi font khi trả kết quả về không có định dạng thẻ meta utf8 bằng cách đặt đoạn code sau ở đầu file.

 

1 header(‘Content-Type: text/html; charset=utf-8’);

 

  1. Khai báo định dạng file

Để khai báo định dạng file thì ta sử dụng cú pháp sau:

 

1 header(“Content-type: text/javascript”);

 

Bạn có thể thay đổi text/javascript thành text/css để khai báo đây là file CSS.

Nếu bạn muốn khi người dùng vào file đó thì sẽ download thay vì hiển thị thì hãy sử dụng thẻ header sau:

 

1

2

header(“Content-type: application/force-download”);

header(“Content-Disposition: attachment; filename=\”download.js\””);

 

  1. Lời kết

Hàm header này tương đối đơn giản, cái khó chính là cấu trúc của chuỗi header phải khai báo chính xác nên bắt buộc ta phải nhớ cấu trúc của nó. Riêng cá nhân mình thì cũng ít khi nhớ lắm, khi nào cần thì lên Google tìm kiếm là ra ngay.

 

504 BÌNH LUẬN

  1. I’m not that much of a online reader to be honest but
    your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back later.
    Cheers

  2. I think other web-site proprietors should take this website as an model, very clean and magnificent user genial style and design, as well as the content. You are an expert in this topic!

  3. Your style is very unique in comparison to other folks I ave read stuff from. Many thanks for posting when you have the opportunity, Guess I all just book mark this page.

  4. Wow, wonderful weblog structure! How long have you ever been running a blog for? you made blogging glance easy. The overall look of your website is magnificent, let alone the content material!

  5. Thanks for the good writeup. It actually used to be a enjoyment account it.
    Look advanced to far delivered agreeable from you!
    By the way, how can we keep in touch?

  6. IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžm a extended time watcher and I just thought IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžd drop by and say hi there there for your quite initially time.

  7. Wow! This could be one particular of the most useful blogs We ave ever arrive across on this subject. Actually Great. I am also an expert in this topic therefore I can understand your effort.

  8. Outstanding post however , I was wondering if you could write a litte more on this subject? I ad be very grateful if you could elaborate a little bit further. Cheers!

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

  10. This particular blog is without a doubt awesome additionally informative. I have picked up a lot of helpful tips out of this source. I ad love to come back again soon. Thanks a lot!

  11. You made some really good points there. I checked on the web for more info about the issue and found most individuals will go along with your views on this website.

  12. This awesome blog is no doubt entertaining and also diverting. I have picked helluva helpful things out of this blog. I ad love to return every once in a while. Cheers!

  13. La excitación sexual masculina es un proceso complejo que involucra al cerebro, las hormonas, las emociones, los nervios, los músculos y los vasos sanguíneos. En los casos de impotencia o de disfunción eréctil nos podemos encontrar con dos situaciones bien diferenciadas. Los resultados de los dos estudios de 6 meses de duración realizados en voluntarios sugieren que este efecto es improbable en humanos.

  14. Usually I don at learn post on blogs, but I would like to say that this write-up very compelled me to take a look at and do it! Your writing style has been surprised me. Thank you, quite nice post.

  15. My brother recommended I might like this web site. He was totally right. This post truly made my day. You can not imagine just how much time I had spent for this information! Thanks!

  16. Nice blog right here! Also your website lots up very fast! What web host are you using? Can I am getting your affiliate hyperlink to your host? I wish my web site loaded up as fast as yours lol

  17. Your style is very unique in comparison to other folks I’ve read stuff from.

    Many thanks for posting when you have the opportunity,
    Guess I’ll just bookmark this page.

  18. I’ll immediately take hold of your rss as I
    can not in finding your e-mail subscription link or e-newsletter service.

    Do you have any? Kindly let me realize so that I could
    subscribe. Thanks.

  19. It’а†s really a great and helpful piece of info. I’а†m glad that you just shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

  20. I’ve been exploring for a bit for any high-quality articles or blog posts
    on this kind of area . Exploring in Yahoo I finally stumbled
    upon this site. Studying this information So i’m satisfied
    to express that I’ve a very excellent uncanny feeling I came upon exactly what I needed.
    I so much undoubtedly will make certain to don?t overlook
    this website and provides it a look on a constant basis.

  21. I’m really impressed with your writing skills as well as with the
    layout on your blog. Is this a paid theme or did you customize it yourself?
    Anyway keep up the excellent quality writing, it is rare to see a nice blog like this one today.

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

  23. It as actually a nice and useful piece of information. I am glad that you simply shared this useful information with us. Please stay us informed like this. Thank you for sharing.

  24. It as really a nice as well as useful piece of information. I am glad that you shared this kind of useful information with us. Please retain us informed such as this. Thanks with regard to sharing.

  25. You can definitely see your enthusiasm within the work you write. The world hopes for more passionate writers like you who are not afraid to mention how they believe. At all times go after your heart.

  26. You have made some decent points there. I checked on the web for more information about the issue and found most individuals will go along with your views on this web site.

  27. This particular blog is no doubt entertaining and besides informative. I have picked a bunch of useful things out of this blog. I ad love to visit it again and again. Thanks a bunch!

  28. You ave made some decent points there. I checked on the internet for additional information about the issue and found most people will go along with your views on this site.

  29. I think this internet site has got some really fantastic info for everyone . аЂа‹аЂ Nothing great was ever achieved without enthusiasm.аЂ аЂа› by Ralph Waldo Emerson.

  30. You completed certain good points there. I did a search on the theme and found the majority of persons will have the same opinion with your blog.

  31. Sweet blog! I found it while surfing around on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I ave been trying for a while but I never seem to get there! Thanks

  32. What as Taking place i am new to this, I stumbled upon this I ave found It absolutely useful and it has aided me out loads. I hope to contribute & assist other customers like its aided me. Good job.|

  33. If you are interested to learn Web optimization techniques then you must read this article, I am sure you will obtain much more from this article regarding SEO.

  34. Howdy! This site post could not be written significantly better! Reading through as a result of this submit jogs my memory of my past roommate! He continually kept preaching about this. I’m planning to forward this text to him. Pretty sure he’ll have an awesome read. I appreciate you for sharing!

  35. Whoa! This blog looks just like my old one! It as on a entirely different topic but it has pretty much the same layout and design. Superb choice of colors!

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

  37. Hi there, I do think your web site might be having internet browser compatibility problems.
    When I look at your site in Safari, it looks fine however,
    when opening in I.E., it has some overlapping
    issues. I just wanted to give you a quick heads up! Aside from that,
    fantastic website!

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

Please enter your comment!
Please enter your name here