简体   繁体   中英

How to check if set_status_header is set to 404 in view in CodeIgniter?

This is how I set header $this->output->set_status_header('404'); in controller:

<?php
class custom404 extends CI_Controller
{
    public function __construct()
    {
            parent::__construct();
    }

    public function index()
    {
        $this->output->set_status_header('404');
        $this->view_data['page_title'] = 'Page not found';
        $this->view_data['main_content'] = 'error404';
        $this->load->view('template', $this->view_data);
    }
}
?>

Then I need to somehow check status header 404 in the view?

Any advice beside sending another variable in $this->view_data?

Create a file called MY_Output.php in your application/core folder with the following code:

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class MY_Output extends CI_Output {

    function set_status_header($code = 200, $text = '')
    {
        set_status_header($code, $text);
        $this->last_set_status_code = $code;
        return $this;
    }

    function get_status_header()
    {
        return $this->last_set_status_code;
    }

}

?>

You can now echo out the last status code you set like so:

$this->output->set_status_header('404');
echo $this->output->last_set_status_code; // outputs '404'
// or get it like so:
echo $this->output->get_status_header(); // outputs '404'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM