第三課起步:掌握 include()/require() 模組化代碼,奠定可維護架構基礎。
| 特性 | require() | include() |
|---|---|---|
| 載入時機 | 腳本啟動前(編譯階段) | 執行到該行時 |
| 條件判斷中 | 無論條件真偽皆載入 | 僅條件為真時載入 |
| 檔案不存在 | 致命錯誤停止執行 | 警告並繼續執行 |
建議:邏輯判斷區塊用 include(),核心配置檔用 require()。
慣用 .inc 為模組副檔名,務必配置 Web 伺服器將 .inc 解析為 PHP,否則駭客可直接瀏覽原始碼(含資料庫密碼等敏感資訊)。
header.inc
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("mydb", $db);
?>
<html><head><title><?php echo $title ?></title></head><body>
<center><h2><?php echo $title ?></h2></center>
footer.inc
</body></html>
主程式
<?php
$title = "Hello World";
include("header.inc");
$result = mysql_query("SELECT * FROM employees", $db);
echo "<table border=1>\n<tr><td>名字</td><td>職位</td></tr>\n";
while ($myrow = mysql_fetch_row($result)) {
printf("<tr><td>%s %s</td><td>%s</td></tr>\n", $myrow[1], $myrow[2], $myrow[3]);
}
echo "</table>\n";
include("footer.inc");
?>
$title,版頭版尾自動套用。