base_url() function won't work on error pages.

2019-04-29 01:56发布

问题:

I want to have nice good looking error pages. For this I need to get some CSS and JS files. But for some odd reason using base_url() does not work on the error_pages. I could of course just use href="/css/style.css" and tell it to get it from the root folder. But the website could very well be put in a different folder than the root folder. So using the / is not an option.

So my question now is why doesn't base_url() work on an error page? I have autoloaded it so shouldn't it be working?

This is what I tried when I was trying to get the base_url() from the error_404 page in the view.

In my autoload.php I have included the helper url

$autoload['helper'] = array('url', 'form');

And in my error_404 page (application/views/errors/html/error_404.php) I am echoing the base_url like so:

<?php echo base_url(); ?>

This is the error I'm getting:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined function base_url()

Filename: /usr/local/www/example.com/application/views/errors/html/error_404.php

Line Number: 37

Backtrace:

    File: /usr/local/www/example.com/index.php
    Line: 315
    Function: require_once

I'd rather not make any changes in the system folder since I don't want to redo the process every time I update Codeigniter folder.

System:

Codeigniter 3.0.6

PHP 7.0.8

Nginx 1.11.1

UPDATE: I'd like to call base_url on every error page (db, 404, general, php, etc.).

回答1:

The autoloader does not work because the autoloader loads the libraries after the error checks are finished. If there are errors like a 404 not found it will view the custom error page without loading the autoloader.

To get your base_url on a custom page you would need to add the following in your custom error page:

$base_url = load_class('Config')->config['base_url'];

Taken from: http://forum.codeigniter.com/thread-65968-post-335822.html#pid335822



回答2:

You must load the helper class to get access url functions. So, try to do first:

$this->load->helper('url');

Then you can echo it using

echo base_url();

alternatively, you can get the same result with

$this->config->config['base_url'];


回答3:

In order to do this ,You must override the error pages in your routes.php file something like

$route['404_override'] = 'controller/method';

And inside method() function,You can access base_url() after loading uri helper as same as normal codeigniter controller.

$this->load->helper('uri');
echo base_url();

if we need to change the design of other php/db error pages.we can edit the following files