Search code examples
phpcodeigniter

How to restrict controller page from direct access from url in Codeigniter?


I have used several codes for restricting direct access of controller page from url, but its not happening. The below code in controller page is not preventing from direct url access. Is there any proper way to prevent from direct access from url?

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
class Cont extends CI_Controller
{
        public function __construct()
        {
            parent ::__construct();
            $this->load->model('test');

        }

       public function handle($function){
            if($function=='abcd'){
                $this->load->view('testpage');
            }
}
}

Solution

  • You can use HTTP_REFERER which holds the information(address) about the page that referred you to the current page, if it's empty you can redirect it to your 404 page. Also, you should always check for $_SESSION and redirect if not set.

    if( !isset($_SERVER['HTTP_REFERER'])) {
    
        $this->load->helper('url');
        redirect('/page404');
    
    }
    

    Alternatively, you can also use HTTP_X_FORWARDED_FOR, but it won't help you in AJAX request. Read more about it here and here.