首页 > 解决方案 > 如何从 CodeIgniter 的文件 config.php 而不是从 CI 控制器获取 $config['imgURL_Path'] 值?

问题描述

我想获得一些常量,在 /application/config/config.php 的 CodeIgnitor 中定义,但是当我在 CI 控制器之外时。例如,我有一个在 CodeIgniter mvc 框架之外生成图像缩略图或其他东西的文件。因为文件 /application/config/config.php 有一个字符串:

defined('BASEPATH') OR exit('不允许直接脚本访问');

我不能只做这样的事情:

include '/application/config/config.php';
$imgPath = $config['imgURL_Path'];

我试图添加这个字符串,但没有结果:

if (defined('STDIN'))
    {
        chdir(dirname(__FILE__));
    }

    if (($_temp = realpath($system_path)) !== FALSE)
    {
        $system_path = $_temp.'/';
    }
    else
    {
        // Ensure there's a trailing slash
        $system_path = rtrim($system_path, '/').'/';
    }

    // Is the system path correct?
    if ( ! is_dir($system_path))
    {
        header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
        echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
        exit(3); // EXIT_CONFIG
    }

define('BASEPATH', str_replace('\\', '/', $system_path));
include '/application/config/config.php';
$imgPath = $config['imgURL_Path'];

我还尝试使用以下内容制作文件 ci.php:

<?php
// file: ci.php
ob_start();
require_once '../index.php'; 
ob_get_clean();
return $CI;
?>

并像这样使用它:

$CI = require_once 'ci.php';
$imgPath = $CI->config->item('imgURL_Path');

但也没有运气。有什么解决办法?

标签: codeigniter

解决方案


如果你想要一个可以在任何地方访问的 URL_path 或变量,你可以使用 helper。

1 在文件夹中创建一个文件helpers,假设您将其命名myvariable_helper.php//确保在 .php 之前添加“_helper”

2 打开autoloadconfig 文件夹,然后搜索$autoload['helper'] ,将新创建的助手插入其中,如下所示:$autoload['helper'] = array(url, myvariable)

3 保存自动加载,然后打开myvariable_helper.php,添加一个函数。假设您将 URL 添加到这样的函数中:

<?php

function img_path()
{
    $imgURL_Path = 'www.your_domain.com/image/upload';
    return $imgURL_Path;
}

4 使用函数名称在任何地方(甚至在 MVC 文件夹之外)调用函数,例如:

public function index()
{
    $data['url'] = img_path(); //assign the variable using return value (which is 'www.your_domain.com/image/upload')

    $this->load->view('Your_View', $data); //just for example
}

注意:这个助手不能从浏览器访问(比如你的模型文件夹),所以它是安全的


推荐阅读