找不到图像时创建了Codeigner控制器


Codeigniter controller created when image not found

我在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';

使用一个不是默认的带有不存在图像的控制器,我使用了这个:

// 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);

这样,生成访问索引函数的日志如下:

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

这就是我遇到的问题,创建了Error类的一个实例。

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

不是。我认为正在发生的事情是,由于您使用的是图像的相对路径(并直接在控制器内调用它,这是错误的,因为您在头之前输入了一些东西),您的浏览器将图像直接连接到CI url,从而向服务器发出此请求:

index.php/doesntexist.png

CI(正确地)将其解释为对不存在的控制器的请求,因此它会发出错误类。

你可以在你的实际代码中做(不过我会把图像放在一个视图中):

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

使用绝对路径,或使用url助手中的base_url()方法:

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

这应该告诉服务器获取正确的请求(/test/doesntexist.png),并且不会触发该错误。