Định nghĩa và cách dùng include và require
include
Cấu trúc<?php
include "đường_dẫn_file/tên_file";
?> Ví dụ:<?php include "include/header.php"; ?> <div>Content</div> <?php include "include/footer.php"; ?> Ta thấy nội dung 2 file header.php và footer.php đã được thêm vào. Download file ví dụ include với file không tồn tại<?php include "include/header.php"; ?> // Giả sử file header.php không có
<div>Content</div>
<?php include "include/footer.php"; ?> Warning: include(header.php): failed to open stream: No such file or directory in C:\xampp\htdocs\example\index.php on line 1 Warning: include(): Failed opening 'header.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\example\index.php on line 1 Content Ta thấy trình duyệt gửi cảnh báo, tuy nhiên những PHP vẫn thực thi những đoạn code bên dưới. require
Cấu trúc<?php
require "đường_dẫn_file/tên_file";
?> Ví dụ:<?php require "require/header.php"; ?> <div>Content</div> <?php require "require/footer.php"; ?> Nội dung 2 file header.php và footer.php đã được thêm vào. Download file ví dụ require với file không tồn tại<?php require "require/header.php"; ?> // Giả sử file header.php không có
<div>Content</div>
<?php require "require/footer.php"; ?> Warning: require(header.php): failed to open stream: No such file or directory in C:\xampp\htdocs\example\index.php on line 1 Fatal error: require(): Failed opening required 'header.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\example\index.php on line 1 Ta thấy trình duyệt gửi cảnh báo, và những đoạn code bên dưới đã không được thực thi. PHP include và require với pathLưu ý: nếu chưa được cấu hình đường dẫn tương đối (relative path) thì dễ xảy ra lỗi khi dùng Sử dụng đường dẫn tuyệt đốiSử dụng cách này
cần kích hoạt <?php include "http://localhost/include/header.php"; ?> <div>Content</div> <?php include "http://localhost/include/footer.php"; ?> Download file ví dụ Sử dụng DOCUMENT_ROOT<?php include $_SERVER["DOCUMENT_ROOT"] . "/include/header.php"; ?> <div>Content</div> <?php include $_SERVER["DOCUMENT_ROOT"] . "/include/footer.php"; ?> Download file ví dụ
Trong PHP các đoạn code khác nhau bạn có thể bố trí ở nhiều file php khác nhau như là một thư viện, rồi bạn gộp chúng lại trong một file PHP khi Server chạy. Có hai hàm để bạn làm điều này đó là Hàm include()Hàm <a href="/">Home</a> - <a href="/lap-trinh-php/">Lập trình PHP</a> - <a href="/html/">HTML</a> - <a href="/contact/">Liên hệ</a> <br /> Với file <html> <body> <?php include("menu.php"); ?> <p>Đây là ví dụ về lệnh include()!</p> </body> </html> Chạy
file trên sẽ có kết quả mà nội dung của Home - Lập trình PHP - HTML - Liên hệ Đây là ví dụ về lệnh include()! Hàm require()Tác dụng của hàm Hàm require_once()Hàm |