首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

CodeIgniter 中 site_url() 與 base_url() 差異完整解析

     編輯:PHP 綜合知識

核心差異一覽

在 CodeIgniter 開發中,site_url() 與 base_url() 是兩個常用但易混淆的 URL 產生函式。其關鍵差異在於是否包含 index_page(預設為 index.php)。

設定前提

$config['base_url']    = "https://domain.com/";
$config['index_page']  = "index.php";

實際輸出比較

呼叫方式實際產生 URL說明
site_url("news/php/2")https://domain.com/index.php/news/php/2包含 index.php
base_url("news/php/2")https://domain.com/news/php/2不含 index.php

使用時機建議

  • site_url():產生指向 Controller/Method 的連結、表單 action、重導向網址,確保路由正確解析。
  • base_url():引用靜態資源(CSS、JS、圖片)、API 端點、或已配置 URL Rewrite 隱藏 index.php 的環境。

補充提醒

若在 config.php 將 $config['index_page'] = ''(配合 Apache mod_rewrite 或 Nginx rewrite 隱藏 index.php),兩者輸出將趨近一致,但語意上仍建議依用途區分使用,維持程式碼可讀性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved