Как я могу перенаправить на страницу администрирования / входа с другой страницы вне папки приложения в codeigniter - PullRequest
1 голос
/ 14 мая 2019

У меня есть несколько файлов, которые я создал вне папки приложения в codeigniter. Ниже приведена структура моих папок и файлов enter image description here

sys_config.php - это файл по умолчанию, который перенаправляет либо в b0a.php , либо в admin / login в папке приложения , если выполняется условие.

sys_config.php code

 $sql ="SELECT host FROM tray WHERE host = '$host'";

       $ret = mysqli_query($mysqli,$sql);
       $row = mysqli_fetch_array($ret);

      if ($row['host'] != '' && $row['host'] == $host) {

        redirect("index", true);
    } else {
        //echo "<p>Nothing matched your query.</p>";
        redirect("b02.php", true);

    }

В install.php под контроллером у меня это

<?php

Class Install extends CI_Controller {

    function __construct()
    {
        parent::__construct();

        //load in some helpers
        $this->load->helper(array('form', 'file', 'url','language'));

        if($this->session->userdata('lang')!="")
        {
            $this->lang->load('admin',$this->session->userdata('lang'));
        }else{
            $this->lang->load('admin', 'english');
        }

        //if this system is already installed redirect to the homepage
        if(file_exists(FCPATH.'application/config/setup.php'))
        {
            //redirect('admin/login');
            redirect('sys_config');
        }

    $this->load->library('form_validation');
    $this->load->library('session');
    }

    function index()
    {
        //build our checks
        $data = array();
        //Destroy All Session
        $this->session->sess_destroy();
        //check for writable folders
        $data['is_writeable']['root'] = is_writeable(FCPATH);
        $data['is_writeable']['config'] = is_writeable(FCPATH.'application/config/');
        $data['is_writeable']['uploads'] = is_writeable(FCPATH.'uploads/');

        $this->form_validation->set_rules('hostname', 'Hostname', 'required');
        $this->form_validation->set_rules('database', 'Database Name', 'required');
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'trim');
        $this->form_validation->set_rules('prefix', 'Database Prefix', 'trim');

        $this->form_validation->set_rules('ssl_support');
        $this->form_validation->set_rules('mod_rewrite');

        if ($this->form_validation->run() == FALSE)
        {
            $data['errors'] = validation_errors();
            $this->load->view('install', $data);
        }
        else
        {
            // Unset any existing DB information
            unset($this->db);

            //generate a dsn string
            $dsn = 'mysqli://'.$this->input->post('username').':'.$this->input->post('password').'@'.$this->input->post('hostname').'/'.$this->input->post('database');

            //connect!
            $this->load->database($dsn);

            if (is_resource($this->db->conn_id) OR is_object($this->db->conn_id))
            {
                //setup the database config file
                $settings                   = array();
                $settings['hostname']       = $this->input->post('hostname');
                $settings['username']       = $this->input->post('username');
                $settings['password']       = $this->input->post('password');
                $settings['database']       = $this->input->post('database');
                $settings['prefix']         = $this->input->post('prefix');             
                $file_contents              = $this->load->view('templates/database', $settings, true);
                write_file(FCPATH.'application/config/database.php', $file_contents);
                $setup_file = "//This Is Setup File";
                write_file(FCPATH.'application/config/setup.php',$setup_file);
                //setup the CodeIgniter default config file

                $config_index               = array('index'=>'index.php');
                if($this->input->post('mod_rewrite'))
                {
                    $config_index           = array('index'=>'');
                }
                $file_contents              = $this->load->view('templates/config', $config_index, true);
                write_file(FCPATH.'application/config/config.php', $file_contents);



                //setup the .htaccess file
                if($this->input->post('mod_rewrite'))
                {
                    $subfolder = trim(str_replace($_SERVER['DOCUMENT_ROOT'], '', FCPATH), '/').'/';
                    $file_contents              = $this->load->view('templates/htaccess', array('subfolder'=>$subfolder), true);
                    write_file(FCPATH.'.htaccess', $file_contents);
                }
                $this->load->library('migration');

                if ( ! $this->migration->current())
                {
                    show_error($this->migration->error_string());
                }

                //redirect to the admin login
                redirect('register');
            }
            else
            {
                $data['errors'] = '<p>A connection to the database could not be established.</p>';
                $this->load->view('install', $data);
            }
        }
    }

}

Я перенаправляю на sys_config, который находится вне папки приложения, используя:

//if this system is already installed redirect to the homepage
        if(file_exists(FCPATH.'application/config/setup.php'))
        {
            //redirect('admin/login');
            redirect('sys_config');
        }

Все работало нормально. Но теперь я попытался перенаправить обратно к admin / login, который дает мне:

Эта страница не работает, localhost перенаправлял вас слишком много раз. Пытаться очистить ваши куки. ERR_TOO_MANY_REDIRECTS

index.php

<?php

    define('ENVIRONMENT', 'development');
/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 */

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'development':
            error_reporting(E_ALL);
        break;

        case 'testing':
        case 'production':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

/*
 *---------------------------------------------------------------
 * SYSTEM FOLDER NAME
 *---------------------------------------------------------------
 */
    $system_path = 'system';

/*
 *---------------------------------------------------------------
 * APPLICATION FOLDER NAME
 *---------------------------------------------------------------
 */
    $application_folder = 'application';


    // Set the current directory correctly for CLI requests
    if (defined('STDIN'))
    {
        chdir(dirname(__FILE__));
    }

    if (realpath($system_path) !== FALSE)
    {
        $system_path = realpath($system_path).'/';
    }

    // ensure there's a trailing slash
    $system_path = rtrim($system_path, '/').'/';

    // Is the system path correct?
    if ( ! is_dir($system_path))
    {
        exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME));
    }

/*
 * -------------------------------------------------------------------
 *  Now that we know the path, set the main path constants
 * -------------------------------------------------------------------
 */
    // The name of THIS file
    define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

    // The PHP file extension
    // this global constant is deprecated.
    define('EXT', '.php');

    // Path to the system folder
    define('BASEPATH', str_replace("\\", "/", $system_path));

    // Path to the front controller (this file)
    define('FCPATH', str_replace(SELF, '', __FILE__));

    // Name of the "system folder"
    define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));


    // The path to the "application" folder
    if (is_dir($application_folder))
    {
        define('APPPATH', $application_folder.'/');
    }
    else
    {
        if ( ! is_dir(BASEPATH.$application_folder.'/'))
        {
            exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
        }

        define('APPPATH', BASEPATH.$application_folder.'/');
    }

require_once BASEPATH.'core/CodeIgniter.php';

/* End of file index.php */
/* Location: ./index.php */

Пожалуйста, как я могу перенаправить с sys_config.php на admin / login?

1 Ответ

1 голос
/ 14 мая 2019

Вы должны исключить URL-адрес вашего admin/login из проверки перенаправления .. потому что здесь происходит то, что он перенаправляется на admin/login, который, я считаю, имеет проверку для входа в систему, а затем метод перенаправления, если не вошел в систему, которая не являетсявыполняется, поэтому он перенаправляется на реферер и т. д.

В проверке добавьте, если строка сегмента uri равна admin/login, тогда не перенаправляйте.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...