codeigniter - 如何从 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');
但也没有运气。有什么解决办法?
解决方案
如果你想要一个可以在任何地方访问的 URL_path 或变量,你可以使用 helper。
1 在文件夹中创建一个文件helpers
,假设您将其命名myvariable_helper.php
//确保在 .php 之前添加“_helper”。
2 打开autoload
config 文件夹,然后搜索$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
}
注意:这个助手不能从浏览器访问(比如你的模型文件夹),所以它是安全的
推荐阅读
- excel - 如何根据多行的单元格值合并单元格
- html - 从 PDF 创建图像(PNG 或 JPEG)以及图像中文本的 HTML 图像映射?
- symfony - 如何在 symfony 4 中为从我的数据库中获取的用户分配角色?
- mysql - 如何在不同的查询条件下连接同一张表的列
- excel - 设置过滤器的VBA复选框弹出窗口?
- c# - 无法从 JSON 中检索值,出现“无法将 Newtonsoft.Json.Linq.JArray 转换为 Newtonsoft.Json.Linq.JToken。” 例外
- java - Jackson Deserializer 抛出带有无效 UTF-8 中间字节的 JsonParseException,而反序列化器 String 带有重音符号
- xcode - Xcode bot 报告未注册帐户
- google-apps-script - 没有什么相似的,也是一个不太常见的 Apps 脚本问题
- php - Ajax 提交表单并检索 url