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

CodeIgniter CRUD操作中上传图片至用户专属目录失败问题求助

问题核心错误点

  • 执行顺序颠倒:上传文件操作执行在前,创建用户子目录操作在后,上传时还没有目标子目录,自然无法把文件存入对应目录
  • mkdir()使用错误:传入的参数是上传后的文件名,而非完整的用户子目录路径,也没有用正确的根目录定位规则,容易出现相对路径寻址错误
  • 字段赋值错误:$ajax_data2['img']先后被赋值为整个POST数组、mkdir()的布尔返回值,完全没有存储正确的图片路径
  • 上传文件名配置问题:直接将用户名作为上传文件名,会丢失原文件扩展名,导致文件无法正常识别

修正后的控制器代码

public function insert()
{
    if ($this->input->is_ajax_request()) {
        $this->form_validation->set_rules('id', 'ID', 'required');
        $this->form_validation->set_rules('username', 'UserName', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required');
        $this->form_validation->set_rules('level', 'Level', 'required');
        $this->form_validation->set_rules('salary', 'Salary', 'required');
        $this->form_validation->set_rules('bonus', 'Bonus', 'required');
        if ($this->form_validation->run() == FALSE) {
            $data = array('responce' => 'error', 'message' => validation_errors());
        } else {
            // 第一步:先获取用户名,拼接用户子目录路径
            $username = $this->input->post('username');
            // 用CodeIgniter常量FCPATH定位项目根目录,避免相对路径出错
            $user_upload_path = FCPATH . 'assets/uploads/' . $username . '/';
            // 目录不存在则创建,设置权限为777,递归创建
            if (!is_dir($user_upload_path)) {
                mkdir($user_upload_path, 0777, true);
            }
            
            // 第二步:配置上传参数,路径指定到刚创建的用户子目录
            $config['upload_path'] = $user_upload_path;
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size']     = '1000';
            // 保留原文件扩展名,避免文件失效
            $ext = pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION);
            $config['file_name'] = $username . '.' . $ext;

            $this->load->library('upload', $config);
            // 重置上传配置,避免之前的配置残留
            $this->upload->initialize($config);
            
            if (!$this->upload->do_upload("img")) {
                $data = array('responce' => "error", 'message' => $this->upload->display_errors());
            } else {
                // 获取上传成功后的文件信息
                $upload_data = $this->upload->data();
                $img_path = 'assets/uploads/' . $username . '/' . $upload_data['file_name'];
                
                $ajax_data = array(
                    'id'=>$this->input->post('id'),
                    'username'=>$username,
                    'email'=>$this->input->post('email'),
                    'password'=>md5($this->input->post('password')), // 建议替换为password_hash更安全
                    'level'=>$this->input->post('level')
                );
                $ajax_data2 =array(
                    'id'=>$this->input->post('id'),
                    'salary'=>$this->input->post('salary'),
                    'bonus'=>$this->input->post('bonus'),
                    'img'=> $img_path // 存储正确的图片访问路径
                );

                if ($this->login_model->insert_entry($ajax_data,$ajax_data2)) {
                    $data = array('responce' => "success", 'message' => "Data added successfully");
                } else {
                    $data = array('responce' => "error", 'message' => "Failed to add data");
                }
            }
            echo json_encode($data);
        }
    } else {
        echo "No direct script access allowed";
    }
}

额外注意事项

  • 确保assets/uploads目录的权限设置为777,否则PHP无法创建子目录和写入文件
  • 现有代码用MD5存储密码安全性极低,生产环境建议替换为PHP原生的password_hash()和password_verify()方法
  • 用户名建议做过滤处理,避免出现特殊字符导致目录创建失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:54:05