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

CodeIgniter图片无法上传至文件夹:Undefined variable $file_name报错

问题分析与修复方案

核心问题

  1. 变量未初始化:$file_name仅在上传成功的if分支内定义,若上传失败(或未选择文件),变量不存在,导致插入数据库时报错。
  2. 变量拼写错误:成功分支里的$data['response'] = 'successfully uploaded '.$filename;中,$filename应为$file_name。
  3. 数组覆盖:后续重新赋值$data = array(...)会覆盖之前的上传响应数据。
  4. 未检查文件是否存在:用户可能未选择图片就提交表单,直接执行上传会触发错误。
  5. 文件名冲突风险:直接使用$_FILES['img']['name']作为文件名,若有重名文件会覆盖原有文件。

修复后的Model代码

public function save() {
    // 初始化$file_name,避免未定义错误
    $file_name = '';
    $response = '';

    // 检查是否有文件上传
    if (!empty($_FILES['img']['name'])) {
        // 设置上传配置
        $config['upload_path'] = './assets/images'; 
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size'] = 100; // 单位KB
        // 生成唯一文件名,避免重名
        $config['file_name'] = uniqid() . '_' . $_FILES['img']['name'];
        
        // 加载上传库
        $this->load->library('upload', $config);
        
        // 执行上传
        if ($this->upload->do_upload('img')) {
            $uploadData = $this->upload->data();
            $file_name = $uploadData['file_name'];
            $response = '图片上传成功';
        } else {
            $response = '上传失败:' . $this->upload->display_errors();
            // 若上传失败,可选择终止插入或存入空值,这里选择继续插入空值
        }
    } else {
        $response = '未选择图片';
    }

    // 准备插入数据库的数据
    $insert_data = array(
        'Name' => $this->input->post('Fname'),
        'Fname' => $this->input->post('Lname'),
        'age' => $this->input->post('Age'),
        'image' => $file_name
    );

    // 插入数据
    $this->db->insert('student', $insert_data);

    // 可选:返回响应信息给控制器
    return $response;
}

额外注意事项

  • 文件夹权限:确保./assets/images文件夹有写入权限(Linux下设置为755或777,Windows下勾选写入权限)。
  • 控制器优化:可以接收模型返回的响应信息,提示用户上传状态:
function save() {
    $response = $this->Reg_model->save();
    // 将响应存入session,在视图中显示
    $this->session->set_flashdata('message', $response);
    redirect(base_url('Reg_form/index'), 'refresh');
}
  • 表单验证:在控制器中添加表单验证,确保必填字段和文件类型符合要求:
$this->form_validation->set_rules('Fname', 'First Name', 'required');
$this->form_validation->set_rules('Lname', 'Last Name', 'required');
if ($this->form_validation->run() == FALSE) {
    // 验证失败,返回表单页面
    $this->load->view('your_form_view');
} else {
    $this->Reg_model->save();
    redirect(base_url('Reg_form/index'));
}

内容的提问来源于stack exchange,提问作者Muhammed Uzair KIM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:43:10