2012-03-06 75 views
0

我在CodeIgniter中遇到了問題,那就是當在服務器上找不到圖像時,會創建一個控制器實例(除了稱爲視圖的實例)。未找到圖像時創建的Codeigniter控制器

我知道這一切聽起來令人困惑,所以這是觀察我在說什麼的代碼。我這樣做,變成一個乾淨的2.1.0版本CI:

添加控制器覆蓋的404錯誤頁面,我加了這樣一句:

// add application/controllers/Errors.php 
Class Errors extends CI_Controller { 

    public function error_404() { 
     echo 'error'; 
    } 
} 
// change routes.php 
$route['404_override'] = 'Errors/error_404'; 

使用一個控制器,它不是默認的用一個unexisting圖像,我用這個:

// add application/controllers/Foo.php 
Class Foo extends CI_Controller { 

    public function index() { 
     echo '<img src="doesntexist.png" />'; 
    } 

} 

我無法弄清楚調試它的另一種方式,所以我創建了一個日誌上寫上CodeIgniter.php事件:

// add on CodeIgniter.php line 356 
$path = 'log.txt'; //Place log where you can find it 
$file = fopen($path, 'a'); 
fwrite($file, "Calling method {$class}/{$method} with request {$_SERVER['REQUEST_URI']}\r\n"); 
fclose($file); 

有了這個,那個產生訪問index功能的記錄如下:

Calling method Foo/index with request /test/index.php/Foo 
Calling method Errors/error_404 with request /test/index.php/doesntexist.png 

這是我有問題,創建Error類的一個實例。

回答

0
that is that when an image is not found on the server, the instance of a controller is created 

不是。我相信發生的事情是,由於您正在使用圖像的相對路徑(並且直接在控制器內調用它,這是錯誤的,因爲您在標題之前輸出了某些東西),您的瀏覽器將圖像直接附加到CI的URL,從而使這一請求給服務器:它是(正確地)由CI解釋爲對一個控制器,該控制器不存在,並且因此發出錯誤類的請求

index.php/doesntexist.png 

你可以做,在你的實際代碼(我把圖像在視圖中,雖然):使用

echo '<img src="/doesntexist.png" />' 

的absoluth路徑,或使用從URL幫手BASE_URL()方法:

echo '<img src="'.base_url().'doesntexist.png" /> 

這應該告訴服務器以獲取正確的請求(/test/doesntexist.png),並不會觸發該錯誤。