整理 CodeIgniter 開發的核心原則與實戰技巧,涵蓋架構設計、安全防護、效能優化、模板渲染、資料庫操作等面向。
/var/www/project/ ├── application/ # 應用程式(放在 webroot 外最佳) ├── system/ # CI 核心(放在 webroot 外最佳) ├── public_html/ # Web 根目錄 │ ├── index.php # 入口檔 │ ├── assets/ # CSS/JS/圖片 │ └── .htaccess # Rewrite 規則 └── logs/ # 應用日誌(不可 Web 存取)
index.php 中設定:
$system_path = '../system'; $application_folder = '../application';
// application/config/database.php
$db['default']['db_debug'] = (ENVIRONMENT !== 'production');
// 入口檔或 hooks 中
if (ENVIRONMENT === 'production') {
ini_set('display_errors', 'Off');
error_reporting(0);
} else {
ini_set('display_errors', 'On');
error_reporting(E_ALL);
}
| 威脅 | CI 內建防護 | 啟用方式 |
|---|---|---|
| SQL Injection | Active Record / Query Builder | 使用 $this->db->where() 等方法,避免手寫 SQL |
| XSS | 全域/單點過濾 | $config['global_xss_filtering'] = TRUE; 或 $this->input->post('key', TRUE) |
| CSRF | CSRF Token | $config['csrf_protection'] = TRUE; 表單用 form_open() |
| 垃圾留言/註冊 | CAPTCHA | 載入 captcha_helper,驗證 $this->input->post('captcha') |
// 網頁快取
$this->output->cache(n); // 快取 n 分鐘
// 資料庫查詢快取
$this->db->cache_on();
$query = $this->db->get('table');
$this->db->cache_off();
// 片段快取(需第三方庫或自行實作)
// 禁止快取 (AJAX、動態頁)
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Pragma: no-cache");
// 長期快取 (靜態資源)
$this->output->set_header('Cache-Control: max-age=2592000');
$this->output->set_header('Expires: ' . gmdate('D, d M Y H:i:s', time()+2592000) . ' GMT');
<?php
// application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
protected $_data = array();
protected $_tplext = '.php';
protected $_header = 'templates/header';
protected $_footer = 'templates/footer';
public function __construct() {
parent::__construct();
$this->_data['title'] = config_item('site_name');
if (ENVIRONMENT === 'development') {
$this->output->enable_profiler(TRUE);
}
}
protected function _view($view, $data = array()) {
$this->load->view($this->_header, $this->_data);
$this->load->view($view, array_merge($this->_data, $data));
$this->load->view($this->_footer);
}
}
// 控制器使用
class Welcome extends MY_Controller {
public function index() {
$this->_data['title'] = '首頁';
$this->_view('welcome_message');
}
}
?>
get_instance() 取得 CI 超級物件index.php:定義路徑常數、載入 system/codeigniter/CodeIgniter.phpCodeIgniter.php:載入核心類、Benchmark、Hooks、Config、URI、Router、Output