You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CI4中如何在视图中显示redirect()->to()->with()传递的闪存数据

解决方案

针对CodeIgniter 4版本

你的重定向代码写法是正确的,但视图里的session调用要适配CodeIgniter的规则,同时要确保项目已正确配置Session服务(默认配置已生效,可检查app/Config/App.php里的sessionDriver相关设置)。

视图里正确的调用方式有两种:

  1. 用session判断并获取数据:
<?php if (session()->has('msg')) : ?>
    <div><?= esc(session()->get('msg')) ?></div>
<?php endif; ?>
  1. 专门获取flash类型的一次性数据(redirect()->with()默认设置的就是这类会自动销毁的flash数据):
<?php $msg = session()->getFlashdata('msg');
if ($msg) : ?>
    <div><?= esc($msg) ?></div>
<?php endif; ?>

针对CodeIgniter 3版本

CI3不支持redirect()->to()->with()的链式写法,需要先设置flashdata再执行重定向:

$this->session->set_flashdata('msg', 'You are not allowed to access that category.');
redirect(base_url('categories'));

然后在视图里这样调用:

<?php if ($this->session->flashdata('msg')) : ?>
    <div><?= $this->session->flashdata('msg') ?></div>
<?php endif; ?>

通用注意事项

  • CI4:确保全局session()函数可正常使用,或已通过use CodeIgniter\Session\Session;引入Session类。
  • CI3:确保控制器继承了CI_Controller,且application/config/autoload.php里已自动加载session库($autoload['libraries'] = array('session');)。

内容的提问来源于stack exchange,提问作者elimariaaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 16:25:33